//+------------------------------------------------------------------+
//| 东北路 EA - MQL5版本
//| 基于MQL4东北路源码转换
//| Copyright 2024
//+------------------------------------------------------------------+
#property copyright "东北路 EA MQL5版本"
#property link      ""
#property version   "1.00"
#property description "东北路网格交易EA - 基于平均价格回归的非趋势相关货币对交易"

// 包含文件
#include <Trade/Trade.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/AccountInfo.mqh>

//+------------------------------------------------------------------+
//| 枚举定义 - 与原MQL4保持一致
//+------------------------------------------------------------------+

// 策略类型枚举 (原TypeOfSets)
enum EnumStrategyType
{
    STRATEGY_SINGLE = 0,                    // 单一策略
    STRATEGY_CUSTOM = 1,                    // 自定义策略
    STRATEGY_1_3ADVISORS = 2,               // 1个3顾问策略
    STRATEGY_2_3ADVISORS = 3,               // 2个3顾问策略
    STRATEGY_3_3ADVISORS = 4,               // 3个3顾问策略
    STRATEGY_123_BIG_9ADV = 5,              // 123大9顾问策略
    STRATEGY_123_SMALL_3ADV = 6,            // 123小3顾问策略
    STRATEGY_123_SBIG_15ADV = 7             // 123大15顾问策略
};

// 新年周末枚举 (原NY_Weekends)
enum EnumNewYearWeekends
{
    NY_DAYS_14 = 0,                         // 14天
    NY_DAYS_7 = 1,                          // 7天
    NY_DAYS_0 = 2                           // 0天
};

// 首仓类型枚举 (原FirstPositiontype)
enum EnumFirstPositionType
{
    FIRST_POS_LONG_AND_SHORT = 1,          // 多空都开
    FIRST_POS_LONG = 2,                    // 只开多
    FIRST_POS_SHORT = 3,                   // 只开空
    FIRST_POS_NOT_OPEN = 4                 // 不开仓
};

// 资金基础类型枚举 (原TypeBFLC)
enum EnumBalanceBaseType
{
    BALANCE_BASE_EQUITY = 0,               // 基于权益
    BALANCE_BASE_BALANCE = 1               // 基于余额
};

// 订单类型枚举 (原typeord)
enum EnumOrderType
{
    EA_ORDER_TYPE_ALL = -1,                // 所有订单
    EA_ORDER_TYPE_BUY = 0,                 // 买单
    EA_ORDER_TYPE_SELL = 1,                // 卖单
    EA_ORDER_TYPE_BUY_LIMIT = 2,           // 限价买单
    EA_ORDER_TYPE_SELL_LIMIT = 3,          // 限价卖单
    EA_ORDER_TYPE_BUY_STOP = 4,            // 停损买单
    EA_ORDER_TYPE_SELL_STOP = 5            // 停损卖单
};

//+------------------------------------------------------------------+
//| 策略配置结构体 (原_sets)
//+------------------------------------------------------------------+
struct S_StrategyConfig
{
    string strategy_name;                   // 策略名称 (原st_1)
    int parameter_1;                        // 参数1 (原in_2)
    double parameter_2;                     // 参数2 (原do_3)
    double parameter_3;                     // 参数3 (原do_4)
    double parameter_4;                     // 参数4 (原do_5)
    double parameter_5;                     // 参数5 (原do_6)
    double parameter_6;                     // 参数6 (原do_7)
    double parameter_7;                     // 参数7 (原do_8)
    
    // 方法声明 (原_sets_8到_sets_11)
    void InitializeStrategy8();
    void InitializeStrategy9();
    void InitializeStrategy10();
    void InitializeStrategy11();
};

//+------------------------------------------------------------------+
//| 输入参数 - 与原MQL4 extern变量对应
//+------------------------------------------------------------------+

// 基础设置组
input group "=========基础设置========="
input string MultiCurrency = "";            // 多货币模式设置
input string CustomStrategyConfig = "";     // 自定义策略配置 (原CustomSets)
input string CommentPrefix = "new";         // 注释前缀 (原comment)
input EnumFirstPositionType FirstPositionType = FIRST_POS_LONG_AND_SHORT; // 首仓类型 (原FirstPositionp)
input bool FastClose = false;               // 紧急平仓 (原fastClose)
input int ServerNumber = 1;                 // 服务器编号 (原nmbrThisServer)
input EnumNewYearWeekends NewYearHolidays = NY_DAYS_0; // 新年假期 (原holidays)
input bool UseVirtualTP = false;            // 使用虚拟止盈 (原useVirtualTP)

// 资金管理设置组
input group "=========资金管理设置========="
input int MaxOtherMagics = 0;               // 最大其他魔术号 (原MaxOtherMagics)
input int MaxOtherSymbols = 0;              // 最大其他符号 (原MaxOtherSymbols)
input EnumBalanceBaseType BalanceBaseType = BALANCE_BASE_EQUITY; // 资金计算基础 (原BaseForLotCalc)
input double VirtualBalance = 0.0;          // 虚拟余额 (原virtBalance)
input double FixedBalance = 0.0;            // 固定余额 (原fix_balance)
input double USDFor001 = 0.0;               // 0.01手所需美元 (原USD_for_001)
input double InitialLots = 0.01;            // 初始固定手数 (原Lots)
double Lots = 0.01;                         // 当前手数

// 平均设置组
input group "=========平均设置========="
input bool UseUnloss = true;                // 恢复模式 (原UseUnloss)
input double LotsMartinRatio = 2.5;         // 马丁比率 (原LotsMartinp)

// 网格级别设置组
input group "=========网格级别设置========="
input int FirstNumber = 3;                  // 首仓级别 (原FirstNumberp)

//+------------------------------------------------------------------+
//| 全局变量 - 与原MQL4 global变量对应，按顺序排列
//+------------------------------------------------------------------+

// 基础全局变量
string g_version = "1.306";                 // 版本号 (原global_1_st)
S_StrategyConfig g_strategy_configs[];      // 策略配置数组 (原global_2_a_160_ko[])
int g_strategy_type = 7;                    // 策略类型 (原global_3_in)
string g_empty_string = "";                 // 空字符串 (原global_4_st)
int g_max_advisors = 15;                    // 最大顾问数 (原global_5_in)
bool g_enable_trading = true;               // 启用交易 (原global_6_bo)
int g_current_time = 0;                     // 当前时间 (原global_7_in)
int g_max_strategies = 1;                   // 最大策略数 (原global_8_in)
int g_magic_base = -858993459;              // 魔术号基础 (原global_9_in)
int g_time_offset_1 = 1072745676;           // 时间偏移1 (原global_10_in)
int g_time_offset_2 = 1717986918;           // 时间偏移2 (原global_11_in)
short g_short_value = 1072719462;           // 短整数值 (原global_12_sh)

// 执行设置组
string g_execution_settings = "=========执行设置========="; // 执行设置标题 (原global_13_st)
int g_grid_level = 0;
int g_current_strategy = 0;                 // 当前策略 (原global_15_in)
bool g_enable_execution = true;             // 启用执行 (原global_16_bo)
double g_execution_price = 0.0;             // 执行价格 (原global_17_do)
int g_ma_period = 0;                        // 移动平均周期 (原global_18_in)
int g_default_ma_period = 200;              // 默认移动平均周期
int g_atr_period = 14;                      // ATR周期
double g_atr_threshold = 100.0;             // ATR阈值
bool g_trading_allowed = true;              // 交易允许状态
int g_delay_time_1 = 400;                   // 延迟时间1 (原global_19_in)
int g_delay_time_2 = 800;                   // 延迟时间2 (原global_20_in)
double g_stddev_multiplier = 1.4;           // 标准差倍数 (原global_21_do)
int g_stddev_period = 14;                   // 标准差周期 (原global_22_in)
double g_point_value = 0.0143;              // 点值 (原global_23_do)
bool g_use_dynamic_stddev = true;           // 使用动态标准差 (原global_24_bo)
int g_current_magic = 0;                    // 当前魔术号 (原global_25_in)
int g_virtual_magic = 0;                    // 虚拟魔术号 (原global_26_in)
int g_strategy_index = 0;                   // 策略索引 (原global_27_in)
double g_virtual_tp_coeff1 = 0.7;           // 虚拟止盈系数1 (原global_28_do)
double g_virtual_tp_coeff2 = 0.9;           // 虚拟止盈系数2 (原global_29_do)
int g_unlock_percent = 70;                  // 解锁百分比 (原global_30_in)
double g_tp_price_coefficient = 1.5;        // 止盈价格系数 (原global_31_do)
double g_martin_coefficient = 2.5;          // 马丁系数 (原global_42_do，对应LotsMartinp)
double g_lot_divider = 0.9;                 // 手数除数 (原global_32_do)
double g_virtual_tp_coeff3 = 0.0;           // 虚拟止盈系数3 (原global_33_do)
double g_virtual_tp_coeff4 = 0.0;           // 虚拟止盈系数4 (原global_34_do)
double g_lot_multiplier = 1.0;              // 手数倍数 (原global_35_do)
double g_symbol_coefficient = 1.0;          // 符号系数 (原global_36_do)
double g_max_lot = 100.0;                   // 最大手数 (原global_37_do)

// 手数限制设置
string g_lot_limit_settings = "Настройки ограничения лота"; // 手数限制设置标题 (原global_38_st)
bool g_enable_lot_limit = true;             // 启用手数限制 (原global_39_bo)
double g_lot_limit_value = 100.0;           // 手数限制值 (原global_40_do)
bool g_enable_grid_trading = true;          // 启用网格交易 (原global_41_bo)
double g_grid_distance = 0.0;               // 网格距离 (原global_69_do)
int g_min_real_level = 70;                  // 最小真实级别 (原global_43_in)
int g_max_martin_steps = 50;                // 最大马丁步数 (原global_44_in)
int g_unlock_grid_level = 6;                // 解锁网格级别 (原global_45_in)

// 测试设置组
string g_tester_settings = "=========测试设置========="; // 测试设置标题 (原global_46_st)
bool g_enable_test_mode = false;            // 启用测试模式 (原global_47_bo)
bool g_enable_visual_mode = true;          // 启用可视化模式 (原global_48_bo)
bool g_enable_optimization = false;         // 启用优化模式 (原global_49_bo)
string g_current_symbol = "";               // 当前符号 (原global_50_st)
int g_symbol_index = 0;                     // 符号索引 (原global_51_in)
int g_strategy_count = 0;                   // 策略计数 (原global_52_in)
double g_virtual_tp_price = 0.0;            // 虚拟止盈价格 (原global_53_do)
int g_tp_level = 0;                         // 止盈级别 (原global_54_in)
double g_upper_band = 0.0;                  // 上轨 (原global_55_do)
double g_ma_value = 0.0;                    // 移动平均值 (原global_56_do)
double g_lower_band = 0.0;                  // 下轨 (原global_57_do)
double g_stddev_value = 0.0;                // 标准差值 (原global_58_do)
int g_band_type = 0;                        // 轨道类型 (原global_59_in)
int g_signal_type = 0;                      // 信号类型 (原global_60_in)
int g_order_type = 0;                       // 订单类型 (原global_61_in)
int g_position_type = 0;                    // 持仓类型 (原global_62_in)
int g_magic_type = 0;                       // 魔术号类型 (原global_63_in)
int g_symbol_type = 0;                      // 符号类型 (原global_64_in)
int g_strategy_type_2 = 0;                  // 策略类型2 (原global_65_in)
int g_grid_type = 0;                        // 网格类型 (原global_66_in)
int g_tp_type = 0;                          // 止盈类型 (原global_67_in)
int g_sl_type = 0;                          // 止损类型 (原global_68_in)
double g_temp_grid_distance = 0.0;          // 临时网格距离计算 (原global_70_in)
int g_trading_signal = 0;                   // 交易信号 (原global_71_in)
double g_signal_price = 0.0;                // 信号价格 (原global_72_in)
int g_signal_level = 0;                     // 信号级别 (原global_73_in)
int g_signal_magic = 0;                     // 信号魔术号 (原global_74_in)
int g_signal_symbol = 0;                    // 信号符号 (原global_75_in)
int g_signal_strategy = 0;                  // 信号策略 (原global_76_in)
bool g_virtual_order_state = false;         // 虚拟订单状态 (原global_77_bo)

// 数组变量
int g_time_array[100][15];                  // 时间数组 (原global_78_in_si100si15)
int g_array_counter_1 = 0;                  // 数组计数器1 (原global_79_in)
int g_array_counter_2 = 0;                  // 数组计数器2 (原global_80_in)
int g_array_counter_3 = 0;                  // 数组计数器3 (原global_81_in)
int g_array_counter_4 = 0;                  // 数组计数器4 (原global_82_in)
int g_array_counter_5 = 0;                  // 数组计数器5 (原global_83_in)
int g_array_counter_6 = 0;                  // 数组计数器6 (原global_84_in)
double g_test_data[7][10000];               // 测试数据数组 (原global_85_do_si7si10000)
string g_string_array[40000];               // 字符串数组 (原global_86_st_si40000)
int g_int_array[40000];                     // 整型数组 (原global_87_in_si40000)
int g_array_index_1 = 0;                    // 数组索引1 (原global_88_in)
int g_array_index_2 = 0;                    // 数组索引2 (原global_89_in)
int g_array_index_3 = 0;                    // 数组索引3 (原global_90_in)
double g_virtual_tp_calc_1 = 0.0;           // 虚拟止盈计算1 (原global_91_do)
double g_virtual_tp_calc_2 = 0.0;           // 虚拟止盈计算2 (原global_92_do)
string g_temp_string;                       // 临时字符串 (原global_93_st)
int g_temp_index = 0;                       // 临时索引 (原global_94_in)
int g_random_value;                         // 随机值 (原r1)
int g_counter_1 = 0;                        // 计数器1 (原global_95_in)
int g_counter_2 = 0;                        // 计数器2 (原global_96_in)
int g_counter_3 = 0;                        // 计数器3 (原global_97_in)
int g_symbol_count = 1;                     // 符号计数 (原global_98_in)
string g_symbol_list[1];                    // 符号列表 (原global_99_st_si1)
double g_symbol_coefficients[1];            // 符号系数 (原global_100_do_si1)
bool g_is_m15_timeframe = true;             // 是否M15时间框架 (原global_101_bo)

// 继续其他全局变量...
int g_counter_4 = 0;                        // 计数器4 (原global_102_in)
int g_counter_5 = 0;                        // 计数器5 (原global_103_in)
bool g_flag_1 = false;                      // 标志1 (原global_104_bo)
bool g_flag_2 = false;                      // 标志2 (原global_105_bo)
int g_counter_6 = 0;                        // 计数器6 (原global_106_in)
int g_counter_7 = 0;                        // 计数器7 (原global_107_in)
int g_counter_8 = 0;                        // 计数器8 (原global_108_in)
int g_counter_9 = 0;                        // 计数器9 (原global_109_in)
string g_temp_string_1;                     // 临时字符串1 (原global_110_st)
string g_temp_string_2;                     // 临时字符串2 (原global_111_st)
string g_empty_string_1 = "";               // 空字符串1 (原global_112_st)
string g_empty_string_2 = "";               // 空字符串2 (原global_113_st)
int g_magic_offset = 2263842;               // 魔术号偏移 (原global_114_in)
int g_counter_10 = 0;                       // 计数器10 (原global_115_in)
int g_counter_11 = 0;                       // 计数器11 (原global_116_in)
string g_no_drawdown = "no_drawdown";       // 无回撤 (原global_117_st)
int g_counter_12 = 0;                       // 计数器12 (原global_118_in)
int g_counter_13 = 0;                       // 计数器13 (原global_119_in)
string g_empty_string_3 = "";               // 空字符串3 (原global_120_st)
bool g_flag_3 = false;                      // 标志3 (原global_121_bo)
double g_3d_array[6][5][2];                 // 三维数组 (原global_122_do_si6si5si2)
bool g_enable_trading_2 = true;             // 启用交易2 (原global_123_bo)
string g_symbol_array[];                    // 符号数组 (原global_124_st_ko[])
double g_point = 0.0;                       // 点差价值 (原global_125_do = 点值*点大小)
double g_symbol_ask = 0.0;                  // 符号卖价 (ASK价格)
double g_symbol_bid = 0.0;                  // 符号买价 (BID价格)  
double g_symbol_point = 0.0;                // 符号点值 (原global_128_do = POINT)
double g_symbol_spread = 0.0;               // 点值 (原global_129_do = TICK_VALUE)
double g_symbol_commission = 0.0;           // 价格偏差计算值 (原global_130_do)
double g_symbol_spread_points = 0.0;        // 点差点数（计算值）
double g_double_array[];                    // 双精度数组 (原global_131_do_ko[])

// 全局变量定义完成

bool g_set_global_var = false;          // 启用可视化模式 (原global_48_bo)

//+------------------------------------------------------------------+
//| 全局对象
//+------------------------------------------------------------------+
CTrade g_trade;                             // 交易对象
CSymbolInfo g_symbol;                       // 符号信息对象
CPositionInfo g_position;                   // 持仓信息对象

//+------------------------------------------------------------------+
//| 函数声明 - 与原MQL4函数对应，按顺序排列
//+------------------------------------------------------------------+

// 主要事件函数
int OnInit();                               // 初始化函数
void OnTick();                              // 主要交易逻辑
void OnTimer();                             // 定时器事件
int OnDeinit(const int reason);             // 清理函数 (原deinit)

// 交易信号分析函数
int AnalyzeTradingSignal();                 // 交易信号分析 (原lizong_12)

// 技术指标计算函数
void CalculateIndicators();                 // 指标计算 (原lizong_13)

// 订单管理函数
void ModifyOrder(double open_price, double stop_loss, double take_profit, datetime expiration); // 订单修改 (原lizong_14)
int ExecuteBuyOrder(string symbol, int magic, double lot, double price, double stop_loss, int slippage, string comment, double take_profit); // 开买单 (原lizong_15)
int ExecuteSellOrder(string symbol, int magic, double lot, double price, double stop_loss, int slippage, string comment, double take_profit); // 开卖单 (原lizong_15)
void ClosePositions(string symbol, int type, int magic); // 平仓 (原lizong_17)

// 网格交易核心函数
int ExecuteGridStrategy();                  // 网格交易逻辑 (原lizong_19)

// 策略配置管理函数
void InitializeDynamicStdDevParams();       // 初始化动态标准差参数 (原lizong_24)
void InitializeStrategyParams();            // 初始化策略参数 (原lizong_26)


// 辅助工具函数
void ParseMultiCurrencyString(string input_string, string &symbols[]); // 解析多货币字符串 (原xx)
void ParseSymbolCoefficients(string &symbols[], double &coefficients[]); // 解析符号系数 (原xx1)
void CopyStrategyConfigs(S_StrategyConfig &source[], S_StrategyConfig &target[]); // 复制策略配置 (原xx3)
void SwapStrategyConfigs(S_StrategyConfig &config1, S_StrategyConfig &config2); // 交换策略配置 (原yy)
void ModifyOrderTP(int magic, int type, double take_profit); // 修改订单止盈 (原lizongs4)
void InitializeVirtualOrders();             // 初始化虚拟订单 (原lizongs7)
void SetVirtualOrderNumber(string symbol, int magic, int number); // 设置虚拟订单编号 (原SetNUMBER)
void CleanupTestEnvironment();              // 清理测试环境 (原rrr)
void ProcessSpecialLogic(int parameter);    // 特殊逻辑处理 (原lizong80)

// 新增的辅助函数
void InitializeStrategyConfigs();           // 初始化策略配置 (原OnInit中的策略配置部分)
void LoadCustomStrategyConfigs(string config_string); // 加载自定义策略配置 (原lizong_23)
void InitializeInterfaceDisplay();          // 初始化界面显示 (原lizong_26)
string CalculateMagicNumber(string symbol); // 计算魔术号 (原zs1)
string CalculateFullMagicNumber(string strategy_string); // 计算完整魔术号 (原zs2)
string TrimString(string str);            // 字符串修剪 (原abc)

// 辅助检查函数
int CheckPositionCount(int magic, string symbol); // 检查持仓数量 (原lizongs6int)
int CheckStringValue(string value);         // 检查字符串值 (原lizongs6str)

// 添加缺失的函数声明
string GetSymbolName(string symbol);        // 获取符号名称 (原lizongs1)
bool CheckPositionExists(string symbol, int type, int magic, int mode, string comment); // 检查持仓是否存在 (原lizongs2)
double GetPositionVolume(string symbol, int type, int magic); // 获取持仓量 (原lizongs3)
void ModifyTakeProfit(int type, int magic, double take_profit); // 修改止盈 (原lizongs4)
string GetTradingTime();                    // 获取交易时间 (原lizongs5)


int GetOtherMagicsCount(int magic, string symbol); // 获取其他魔术号数量 (原lizongs6int)
int GetOtherSymbolsCount(string symbol);    // 获取其他符号数量 (原lizongs6str)
void UpdateInterface();                     // 更新界面 (原lizongs7)
double GetPositionOpenPrice(int type, int magic); // 获取持仓开仓价格 (原lizongs8)
bool CheckVirtualTakeProfit(int type);      // 检查虚拟止盈 (原lizongs9)
bool CheckTradingConditions();              // 检查交易条件 (原lizongs10)


void ProcessVirtualTakeProfit();            // 处理虚拟止盈 (原lizong_30)
int GetTradingSignal();                     // 获取交易信号 (原lizong_12)
double CalculateLotSize(double base_lot, bool use_martin); // 计算手数 (原lizong_16)
void UpdateVirtualOrder(int order_ticket);  // 更新虚拟订单 (原lizong80)
void UpdateInterfaceDisplay();              // 更新界面显示 (原lizong_27)
string ConvertSymbolToNumber(string symbol_part); // 转换货币符号为数字 (原lizong_20)
string CalculateSymbolCode(string symbol);      // 计算品种代码 (原zs1)
string GetErrorDescription(int error_code);       // 获取错误描述 (原lizong_18)

//+------------------------------------------------------------------+
//| 函数实现 - 空实现，后续逐步完善
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| 初始化函数
//+------------------------------------------------------------------+
int OnInit()
{
    // 初始化Lots
    Lots = InitialLots;
    // 设置终端信息 (原global_102_in = TerminalInfoInteger(27) * 100 / 96)
    g_counter_4 = (int)(TerminalInfoInteger(TERMINAL_SCREEN_DPI) * 100.0 / 96.0);
    
    // 设置定时器 (原EventSetTimer(1))
    EventSetTimer(1);
    
    // 清理测试环境 (原rrr())
    CleanupTestEnvironment();
    
    // 检查时间框架 (原Period() != 15)
    if (Period() != PERIOD_M15)
    {
        Print("EA只能在M15时间框架上运行。请将时间框架改为M15");
        Alert("EA只能在M15时间框架上运行。请将时间框架改为M15并重启EA。");
        g_is_m15_timeframe = false;
    }
    else
    {
        g_is_m15_timeframe = true;
    }
    
    // 初始化符号数组 (原ArrayResize)
    ArrayResize(g_symbol_coefficients, 1, 0);
    ArrayResize(g_symbol_list, 1, 0);
    
    // 处理多货币设置 (原abc(MultiCurrency) != "" && !(MQLInfoInteger(MQL_TESTER)))
    string multi_currency_trimmed = TrimString(MultiCurrency);
    if (multi_currency_trimmed != "" && !MQLInfoInteger(MQL_TESTER))
    {
        ParseMultiCurrencyString(multi_currency_trimmed, g_symbol_list);
        ParseSymbolCoefficients(g_symbol_list, g_symbol_coefficients);
    }
    else
    {
        g_symbol_list[0] = _Symbol;
        g_symbol_coefficients[0] = g_lot_multiplier;
    }
    
    // 设置符号数量 (原global_98_in = ArraySize(global_99_st_si1))
    g_symbol_count = ArraySize(g_symbol_list);
    
    // 测试模式下设置当前符号 (原MQLInfoInteger(MQL_TESTER))
    if (MQLInfoInteger(MQL_TESTER))
    {
        g_current_symbol = _Symbol;
    }
    
    // 初始化策略配置
    InitializeStrategyConfigs();
    
    // 计算手数系数 (原global_34_do = (USD_for_001 == 0.0) ? 0.0 : 1000.0 / USD_for_001 / global_8_in)
    g_virtual_tp_coeff3 = (USDFor001 == 0.0) ? 0.0 : 1000.0 / USDFor001 / g_max_strategies;
    
    // 设置恢复模式参数 (原!(UseUnloss))
    // 设置恢复模式参数 (原MQ4: if (!(UseUnloss)))
    if (!UseUnloss)
    {
        g_min_real_level = 7;   // 对应MQL4: global_43_in = 7
        g_max_martin_steps = 5;  // 对应MQL4: global_44_in = 5
    }
    
    // 检查是否需要显示界面 (原global_6_bo && (!(MQLInfoInteger(MQL_TESTER)) || IsVisualMode()))
    if (g_enable_visual_mode && (!MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_VISUAL_MODE)))
    {
        // 实现界面显示逻辑 (原lizong_26函数)
        InitializeInterfaceDisplay();
    }
    
    // 初始化动态标准差参数 (原lizong_24())
    InitializeDynamicStdDevParams();
    
    // 隐藏测试指标 (原HideTestIndicators(true))
    ChartSetInteger(0, CHART_SHOW_GRID, false);
    
    // 初始化魔术号和全局变量
    for (int symbol_index = 0; symbol_index < g_symbol_count; symbol_index++)
    {
        g_current_symbol = g_symbol_list[symbol_index];
        for (int strategy_index = 1; strategy_index <= g_max_strategies; strategy_index++)
        {
            string strategy_string = IntegerToString(strategy_index, 2, '0');
            string symbol_code = CalculateSymbolCode(g_current_symbol);
            string server_code = IntegerToString(ServerNumber, 2, '0');
            
            // 计算虚拟魔术号 (用于构建全局变量的键)
            g_virtual_magic = (int)StringToInteger(symbol_code + strategy_string);
            
            // 计算真实魔术号 (用于实际交易)
            g_current_magic = (int)StringToInteger(symbol_code + server_code + strategy_string);
            
            // 将真实魔术号存入以虚拟魔术号为键的全局变量中
            string magic_var_name = IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "Magic" + g_current_symbol + IntegerToString(g_virtual_magic);
            GlobalVariableSet(magic_var_name, g_current_magic);
            
            // 设置初始权益 (原global_85_do_si7si10000[3][0] = AccountEquity())
            if(symbol_index == 0 && strategy_index == 1) // 仅初始化一次
            {
                g_test_data[3][0] = AccountInfoDouble(ACCOUNT_EQUITY);
            }
        }
    }
    
    Print("东北路 EA 初始化完成");
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| 主要交易逻辑
//+------------------------------------------------------------------+
//| 主要交易逻辑 (原OnTick函数)
//+------------------------------------------------------------------+
void OnTick()
{
    // 检查时间框架 (原MQL4: if (!(global_101_bo) && !(MQLInfoInteger(MQL_TESTER))))
    if (!g_is_m15_timeframe && !MQLInfoInteger(MQL_TESTER))
    {
        Print("The adviser adapted only on the M15 period. Change the timeframe to M15");
    }
    
    // 第一个循环：处理开仓逻辑 (原MQL4: for (int local_1_in = 0; local_1_in < global_98_in; local_1_in++))
    for (int symbol_index = 0; symbol_index < g_symbol_count; symbol_index++)
    {
        // 获取当前符号 (原MQL4: global_50_st = lizongs1(global_99_st_si1[local_1_in]))
        g_current_symbol = GetSymbolName(g_symbol_list[symbol_index]); // 原lizongs1
        
        if (g_current_symbol == "")
            continue;
            
        // 设置手数倍数 (原MQL4: global_36_do = global_100_do_si1[local_1_in])
        g_lot_multiplier = g_symbol_coefficients[symbol_index];
        
        // 检查市场信息 (原MQL4: if (MarketInfo(global_50_st, 9) == 0.0))
        if (SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN) == 0.0)
            continue;
            
        int strategy_index = 1; // 原local_2_in = 1
        if (g_max_strategies < 1)
            continue;
            
        // 遍历策略 (原MQL4: for (; local_2_in <= global_8_in; local_2_in++))
        for (; strategy_index <= g_max_strategies; strategy_index++)
        {
            // 虚拟止盈处理 (原MQL4: if (useVirtualTP))
            if (UseVirtualTP)
            {
                if (CheckPositionExists(g_current_symbol, -1, -1, 0, "")) // 原lizongs2
                {
                    UpdateStrategyParameters(strategy_index); // 原lizong_29
                    ProcessVirtualTakeProfit(); // 原lizong_30
                }
            }
            
            // 快速平仓处理 (原MQL4: if (fastClose))
            if (FastClose)
            {
                if (CheckPositionExists(g_current_symbol, -1, -1, 0, "")) // 原lizongs2
                {
                    UpdateStrategyParameters(strategy_index); // 原lizong_29
                    if (GetPositionVolume(g_current_symbol, -1, g_current_magic) > 0.0) // 原lizongs3
                    {
                        ClosePositions(g_current_symbol, -1, g_current_magic); // 原lizong_17
                    }
                }
            }
            
            // 检查时间戳 (原MQL4: if (global_78_in_si100si15[local_2_in][local_1_in] == iTime(global_50_st, 0, 0)))
            if (g_time_array[strategy_index][symbol_index] == iTime(g_current_symbol, 0, 0))
                continue;
                
            UpdateStrategyParameters(strategy_index); // 原lizong_29

            // 如果没有持仓且不满足交易条件，清理虚拟订单状态 (原lizong_19的部分逻辑)
            if (!CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "") && !CheckTradingConditions())
            {
                    if(g_grid_level != 0) {
                        PrintFormat("[GridLevel-Reset] OnTick-A. Magic:%d, From:%d, To:0", g_virtual_magic, g_grid_level);
                        g_grid_level = 0;
                        GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                        GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak", 0.0);
                        ObjectDelete(0, IntegerToString(g_current_magic));
                    }
            }

            // 如果没有持仓但满足交易条件，检查交易时间 (原lizong_19的部分逻辑)
            if (!CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "") && !CheckTradingConditions())
            {
                    if (GetTradingTime() != "" || FirstPositionType == FIRST_POS_NOT_OPEN)
                    {
                        GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "0" + IntegerToString(g_virtual_magic), 0.0);
                        GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "1" + IntegerToString(g_virtual_magic), 0.0);
                        if(g_grid_level != 0) {
                            PrintFormat("[GridLevel-Reset] OnTick-B. Magic:%d, From:%d, To:0", g_virtual_magic, g_grid_level);
                            g_grid_level = 0;
                            GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                            GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak", 0.0);
                            ObjectDelete(0, IntegerToString(g_current_magic));
                        }
                    }
            }
            
            // 测试数据记录 (原MQL4: if (local_2_in == 1 && (global_47_bo || global_49_bo)))
            if (strategy_index == 1 && (g_enable_test_mode || g_enable_visual_mode))
            {
                MqlDateTime dt_current, dt_previous;
                TimeToStruct(iTime(g_current_symbol, 0, 0), dt_current);
                TimeToStruct(iTime(g_current_symbol, 0, 1), dt_previous);
                if (dt_current.day != dt_previous.day && MQLInfoInteger(MQL_TESTER))
                {
                    g_test_data[0][g_array_index_2] = iTime(g_current_symbol, 0, 0);
                    g_test_data[1][g_array_index_2] = AccountInfoDouble(ACCOUNT_BALANCE);
                    g_test_data[2][g_array_index_2] = AccountInfoDouble(ACCOUNT_EQUITY);
                    g_test_data[3][g_array_index_2 + 1] = AccountInfoDouble(ACCOUNT_EQUITY);
                    g_test_data[5][g_array_index_2] = AccountInfoDouble(ACCOUNT_MARGIN) * (AccountInfoInteger(ACCOUNT_LEVERAGE) / 100.0);
                    g_test_data[6][g_array_index_2 + 1] = AccountInfoDouble(ACCOUNT_MARGIN) * (AccountInfoInteger(ACCOUNT_LEVERAGE) / 100.0);
                    g_array_index_2++;
                }
                if (AccountInfoDouble(ACCOUNT_EQUITY) < g_test_data[3][g_array_index_2])
                {
                    g_test_data[3][g_array_index_2] = AccountInfoDouble(ACCOUNT_EQUITY);
                }
                if (AccountInfoDouble(ACCOUNT_MARGIN) * (AccountInfoInteger(ACCOUNT_LEVERAGE) / 100.0) > g_test_data[6][g_array_index_2])
                {
                    g_test_data[6][g_array_index_2] = AccountInfoDouble(ACCOUNT_MARGIN) * (AccountInfoInteger(ACCOUNT_LEVERAGE) / 100.0);
                }
            }
            
            // 虚拟止盈检查 - 买单 (原MQL4: if (lizongs9(0) && MathMax(iHigh(global_50_st, 0, 1), global_127_do) >= GlobalVariableGet(...)))
            // 注意: MQL4中global_127_do虽然是从MarketInfo(MODE_SWAPSHORT)获取，但实际作为BID价格使用
            if (CheckVirtualTakeProfit(0) && MathMax(iHigh(g_current_symbol, 0, 1), g_symbol_bid) >= GlobalVariableGet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "tp")) // 原lizongs9
            {
                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "0" + IntegerToString(g_virtual_magic), 0.0);
                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                ObjectDelete(0, g_current_magic);
            }
            
            // 虚拟止盈检查 - 卖单 (原MQL4: if (lizongs9(1) && MathMin(iLow(global_50_st, 0, 1) + global_126_do - global_127_do, global_126_do) <= GlobalVariableGet(...)))
            // 注意: MQL4中global_126_do是从MarketInfo(MODE_SWAPLONG)获取，但实际作为ASK价格使用
            if (CheckVirtualTakeProfit(1) && MathMin(iLow(g_current_symbol, 0, 1) + g_symbol_ask - g_symbol_bid, g_symbol_ask) <= GlobalVariableGet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "tp")) // 原lizongs9
            {
                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "1" + IntegerToString(g_virtual_magic), 0.0);
                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                ObjectDelete(0, g_current_magic);
            }
            
            // 检查是否需要重置网格级别 (原MQ4: if (!lizongs2 && !lizongs10) { global_14_in = 0; })
            if (!CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "") && !CheckTradingConditions())
            {
                // 只在没有持仓且不满足交易条件时重置网格级别
                if(g_grid_level != 0) {
                    PrintFormat("[GridLevel-Reset] OnTick-C. Magic:%d, From:%d, To:0", g_virtual_magic, g_grid_level);
                   g_grid_level = 0;
                GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                }
            }
            
            if (g_upper_band == 0.0)
                continue;
                
            // 网格交易和指标计算 (原MQL4: if (global_41_bo && global_123_bo))
            if (g_enable_grid_trading && g_enable_trading)
            {
                ExecuteGridStrategy();  // 执行网格交易逻辑 (原lizong_19)
            }
            
                        
            // 获取交易信号 (原MQL4: global_71_in = lizong_12())
            g_trading_signal = GetTradingSignal(); // 原lizong_12
            
            int buy_signal = 0; // 原local_3_in = 0
            double sell_price = 0; // 原local_5_in = 0
            double buy_price = 0; // 原local_7_in = 0
            
            // 检查是否有持仓 (原MQL4: if (lizongs2(global_50_st, -1, global_25_in, 0, "")))
            if (CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "")) // 原lizongs2
                continue;
                
            // 检查交易条件 (原MQL4: if (lizongs10() || !(global_123_bo)))
            
            if (CheckTradingConditions() || !g_enable_trading) // 原lizongs10
                continue;
                
            // 检查交易时间 (原MQL4: if (lizongs5() != ""))
            if (GetTradingTime() != "") // 原lizongs5
                continue;
                
            g_virtual_order_state = false; // 原global_77_bo = false
            int order_ticket = 0; // 原local_8_in = 0
            
            // 买单信号处理 (原MQL4: if (global_71_in == 1))
            if (g_trading_signal == 1)
            {
                int virtual_order = 0; // 原local_9_in = 0
                
                // OnTick中的简单判断 (原MQ4: if (FirstNumberp > global_14_in))
                if (FirstNumber > g_grid_level)
                {   
                    SetGlobalVar("", "0", 1.0);  // 设置虚拟买单
                    virtual_order = 1;
                    order_ticket = -1;
                    // Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " 【tick_buy】 The opened grid level is less than the minimum level. The deal is virtualized");
                }
                else
                {
                    // 检查手数 (原MQL4: if (lizong_16(1.0, true) < 0.01))
                    if (CalculateLotSize(1.0, true) < 0.01) // 原lizong_16
                    {
                        SetGlobalVar("", "0", 1.0);  // 设置虚拟买单
                        virtual_order = 1;
                        order_ticket = -1;
                        Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " Current lot <0.01. The deal is virtualized");
                    }
                    else
                    {
                        // 检查其他魔术号数量 (原MQL4: if (MaxOtherMagics > 0))
                        if (MaxOtherMagics > 0)
                        {
                            if (GetOtherMagicsCount(g_current_magic, "") >= MaxOtherMagics) // 原lizongs6int
                            {
                                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "0" + IntegerToString(g_virtual_magic), 1.0);
                                virtual_order = 1;
                                order_ticket = -1;
                                Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " GetOtherMagicsCount >= MaxOtherMagics. The deal is virtualized");
                            }
                        }
                        else
                        {
                            // 检查其他符号数量 (原MQL4: if (MaxOtherSymbols > 0))
                            if (MaxOtherSymbols > 0)
                            {
                                if (GetOtherSymbolsCount(g_current_symbol) >= MaxOtherSymbols) // 原lizongs6str
                                {
                                    GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "0" + IntegerToString(g_virtual_magic), 1.0);
                                    virtual_order = 1;
                                    order_ticket = -1;
                                    Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " GetOtherSymbolsCountt >= MaxOtherSymbols. The deal is virtualized");
                                }
                            }
                            else
                            {
                                // 执行买单 (原MQL4: local_8_in = lizong_15(global_50_st, 0, lizong_16(1.0, true), 0, 0, global_25_in, "C0", 0.0))
                                order_ticket = ExecuteBuyOrder(CalculateLotSize(1.0, true), "C0"); // 原lizong_15
                                if (order_ticket > 0)
                                {
                                    virtual_order = 1;
                                }
                            }
                        }
                    }
                }
                
                if (virtual_order == 1)
                {
                    g_time_array[strategy_index][symbol_index] = iTime(g_current_symbol, 0, 0); // 精确复刻：下单后立即“上锁”
                    UpdateVirtualOrder(order_ticket); // 原lizong80
                    // 计算临时网格距离 (原MQL4: global_70_in = (global_55_do - global_56_do) / global_128_do)
                    g_temp_grid_distance = (g_upper_band - g_ma_value) / g_symbol_point;
                    
                    // 计算网格距离 (原MQL4: global_69_do = MathMin(iClose(global_50_st, 0, 1), global_127_do) + global_126_do - global_127_do - global_70_in * global_128_do)
                    g_grid_distance = MathMin(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol_bid) + g_symbol_ask - g_symbol_bid - g_temp_grid_distance * g_symbol_point;
                    GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                    GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "Distance_Price" + g_current_symbol + IntegerToString(g_virtual_magic), g_grid_distance);
                    UpdateInterface(); // 原lizongs7
                }
            }
            
            if (g_trading_signal != 2)
                continue;
                
            // 卖单信号处理 (原MQL4: if (global_71_in != 2) continue)
            // 检查最小网格级别 (原MQL4: if (FirstNumberp > global_14_in))
            // Print("Grid Level Check (Sell) - Symbol: ", g_current_symbol,
            //       ", Magic: ", g_current_magic,
            //       ", FirstNumber: ", FirstNumber,
            //       ", Min Real Level: ", g_min_real_level,
            //       ", Current Grid Level: ", g_grid_level,
            //       ", Upper Band: ", g_upper_band,
            //       ", Lower Band: ", g_lower_band,
            //       ", Current Price: ", SymbolInfoDouble(g_current_symbol, SYMBOL_BID));
                  
            // 检查最小网格级别 (原MQ4: if (FirstNumberp > global_14_in))
            if (FirstNumber > g_grid_level)
            {
                    SetGlobalVar("", "1", 1.0);  // 设置虚拟卖单
                    buy_signal = 1;
                    order_ticket = -1;
                    // Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " [tick sell] The opened grid level is less than the minimum level. The deal is virtualized");
            }
            else
            {
                // 检查手数 (原MQL4: if (lizong_16(1.0, true) < 0.01))
                if (CalculateLotSize(1.0, true) < 0.01) // 原lizong_16
                {
                    GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "1" + IntegerToString(g_virtual_magic), 1.0);
                    buy_signal = 1;
                    order_ticket = -1;
                    Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " Current lot <0.01. The deal is virtualized");
                }
                else
                {
                    // 检查其他魔术号数量 (原MQL4: if (MaxOtherMagics > 0))
                    if (MaxOtherMagics > 0)
                    {
                        if (GetOtherMagicsCount(g_current_magic, "") >= MaxOtherMagics) // 原lizongs6int
                        {
                                                            SetGlobalVar("", "1", 1.0);  // 设置虚拟卖单
                                buy_signal = 1;
                                order_ticket = -1;
                                Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " GetOtherMagicsCount >= MaxOtherMagics. The deal is virtualized");
                        }
                    }
                    else
                    {
                        // 检查其他符号数量 (原MQL4: if (MaxOtherSymbols > 0))
                        if (MaxOtherSymbols > 0)
                        {
                            if (GetOtherSymbolsCount(g_current_symbol) >= MaxOtherSymbols) // 原lizongs6str
                            {
                                SetGlobalVar("", "1", 1.0);  // 设置虚拟卖单
                                buy_signal = 1;
                                order_ticket = -1;
                                Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " GetOtherSymbolsCountt >= MaxOtherSymbols. The deal is virtualized");
                            }
                        }
                        else
                        {
                            // 执行卖单 (原MQL4: local_8_in = lizong_15(global_50_st, 1, lizong_16(1.0, true), 0, 0, global_25_in, "C0", 0.0))
                            order_ticket = ExecuteSellOrder(CalculateLotSize(1.0, true), "C0"); // 原lizong_15
                            if (order_ticket > 0)
                            {
                                buy_signal = 1;
                            }
                        }
                    }
                }
            }
            
            if (buy_signal != 1)
                continue;
                
            g_time_array[strategy_index][symbol_index] = iTime(g_current_symbol, 0, 0); // 精确复刻：下单后立即“上锁”
            UpdateVirtualOrder(order_ticket); // 原lizong80
            
            // 计算网格距离
            g_temp_grid_distance = (g_upper_band - g_ma_value) / g_symbol_point; // 原global_70_in = (global_55_do - global_56_do) / global_128_do
            g_grid_distance = g_temp_grid_distance * g_symbol_point + MathMax(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol_bid); // 原global_69_do = MathMax(iClose(global_50_st, 0, 1), global_127_do) + global_70_in * global_128_do
            SetGlobalVar("NUMBER", "", 0.0);  // 重置网格数
            SetGlobalVar("Distance_Price", "", g_grid_distance);  // 设置距离价格
            UpdateInterface(); // 原lizongs7
        }
    }
    
    // 第二个循环：处理平仓逻辑 (原MQL4: for (int local_10_in = 0; local_10_in < global_98_in; local_10_in++))
    for (int symbol_index = 0; symbol_index < g_symbol_count; symbol_index++)
    {
        g_current_symbol = g_symbol_list[symbol_index]; // 原global_50_st = global_99_st_si1[local_10_in]
        g_lot_multiplier = g_symbol_coefficients[symbol_index]; // 原global_36_do = global_100_do_si1[local_10_in]
        
        if (SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN) == 0.0) // 原MarketInfo(global_50_st, 9) == 0.0
            continue;
            
        int strategy_index = 1; // 原local_11_in = 1
        if (g_max_strategies < 1)
            continue;
            
        // 遍历策略 (原MQL4: for (; local_11_in <= global_8_in; local_11_in++))
        for (; strategy_index <= g_max_strategies; strategy_index++)
        {
            // 界面更新 (原MQL4: if (local_11_in == global_8_in && local_10_in == global_98_in - 1 && !(MQLInfoInteger(MQL_TESTER)) && global_6_bo && (!(MQLInfoInteger(MQL_TESTER)) || IsVisualMode())))
            if (strategy_index == g_max_strategies && symbol_index == g_symbol_count - 1 && !MQLInfoInteger(MQL_TESTER) && g_enable_visual_mode && (!MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_VISUAL_MODE)))
            {
                UpdateInterfaceDisplay(); // 原lizong_27
            }
            
            // 检查时间戳 (原MQL4: if (global_78_in_si100si15[local_11_in][local_10_in] == iTime(global_50_st, 0, 0)))
            if (g_time_array[strategy_index][symbol_index] == iTime(g_current_symbol, 0, 0))
                continue;
                
            g_time_array[strategy_index][symbol_index] = iTime(g_current_symbol, 0, 0); // 原global_78_in_si100si15[local_11_in][local_10_in] = iTime(global_50_st, 0, 0)
            
            // 界面更新 (原MQL4: if (local_11_in == global_8_in && local_10_in == global_98_in - 1 && MQLInfoInteger(MQL_TESTER) && global_6_bo && (!(MQLInfoInteger(MQL_TESTER)) || IsVisualMode())))
            if (strategy_index == g_max_strategies && symbol_index == g_symbol_count - 1 && MQLInfoInteger(MQL_TESTER) && g_enable_visual_mode && (!MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_VISUAL_MODE)))
            {
                UpdateInterfaceDisplay(); // 原lizong_27
            }
            
            UpdateStrategyParameters(strategy_index); // 原lizong_29
            
            // 买单平仓逻辑 (原MQL4: if (lizongs2(global_50_st, 0, global_25_in, 0, "") || lizongs9(0)))
            if (CheckPositionExists(g_current_symbol, 0, g_current_magic, 0, "") || CheckVirtualTakeProfit(0)) // 原lizongs2和lizongs9
            {
                // 计算止盈价格 (严格遵循MQL4逻辑)
                g_virtual_tp_calc_1 = MathPow(g_martin_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) * g_unlock_percent / MathPow(g_martin_coefficient, 2.0) * g_symbol.Bid() * 0.00001 + GetPositionOpenPrice(0, g_current_magic);
                g_virtual_tp_calc_2 = MathPow(g_martin_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) * g_unlock_percent / MathPow(g_martin_coefficient, 2.0) * g_symbol.Bid() * 0.00001 + g_virtual_tp_coeff1 * MathPow(g_virtual_tp_coeff2, g_grid_level) * (g_ma_value - g_symbol.Bid()) + g_symbol.Ask();
                
                if (UseUnloss)
                {
                    g_virtual_tp_price = !CheckPositionExists(g_current_symbol, 0, g_current_magic, 0, "") ? g_virtual_tp_calc_2 : MathMax(g_virtual_tp_calc_1, g_virtual_tp_calc_2); // 原global_53_do
                    g_virtual_tp_price = (g_min_real_level >= g_max_martin_steps) ? g_virtual_tp_calc_1 : g_virtual_tp_price; // 原global_53_do
                }
                else
                {
                    g_virtual_tp_price = g_virtual_tp_calc_2; // 原global_53_do = global_92_do
                }
                
                if (!UseVirtualTP)
                {
                    ModifyTakeProfit(0, g_current_magic, g_virtual_tp_price); // 原lizongs4
                }
                else
                {
                    ModifyTakeProfit(0, g_current_magic, 0.0); // 原lizongs4
                }
                
                SetGlobalVar("", "tp", g_virtual_tp_price);  // 设置虚拟止盈价格
                
                double peak_price = GlobalVariableGet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak"); // 原local_12_do
                if ((iLow(g_current_symbol, 0, 1) < peak_price || peak_price == 0.0)) // 原(iLow(global_50_st, 0, 1) < local_12_do || local_12_do == 0.0)
                {
                    peak_price = iLow(g_current_symbol, 0, 1); // 原local_12_do = iLow(global_50_st, 0, 1)
                    GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak", peak_price); // 原GlobalVariableSet
                }
                
                if (g_lower_band - peak_price != 0.0 && (g_upper_band - peak_price) / (g_lower_band - peak_price) > g_unlock_percent) // 原(global_127_do - local_12_do) / (global_56_do - local_12_do) > global_32_do
                {
                    if ((!UseUnloss || (GetPositionVolume(g_current_symbol, 0, g_current_magic) > 0.0 && UseUnloss))) // 原(!(UseUnloss) || (lizongs3(global_50_st, 0, global_25_in) > 0.0 && UseUnloss))
                    {
                        ClosePositions(g_current_symbol, -1, g_current_magic); // 原lizong_17
                        if (!CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "")) // 原!lizongs2(global_50_st, -1, global_25_in, 0, "")
                        {
                            GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "0" + IntegerToString(g_virtual_magic), 0.0);
                            GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
                        }
                    }
                }
            }
            
            // 卖单平仓逻辑 (原MQL4: if (!lizongs2(global_50_st, 1, global_25_in, 0, "")))
            if (!CheckPositionExists(g_current_symbol, 1, g_current_magic, 0, "")) // 原lizongs2
            {
                if (!CheckVirtualTakeProfit(1)) // 原!(lizongs9(1))
                    continue;
            }
            
            // 计算止盈价格 (严格遵循MQL4逻辑)
            g_virtual_tp_calc_1 = GetPositionOpenPrice(1, g_current_magic) - MathPow(g_martin_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) * g_unlock_percent / MathPow(g_martin_coefficient, 2.0) * g_symbol.Bid() * 0.00001;
            g_virtual_tp_calc_2 = g_symbol.Bid() - g_virtual_tp_coeff1 * MathPow(g_virtual_tp_coeff2, g_grid_level) * (g_symbol.Bid() - g_ma_value) - MathPow(g_martin_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) * g_unlock_percent / MathPow(g_martin_coefficient, 2.0) * g_symbol.Bid() * 0.00001;
            
            if (UseUnloss)
            {
                g_virtual_tp_price = !CheckPositionExists(g_current_symbol, 1, g_current_magic, 0, "") ? g_virtual_tp_calc_2 : MathMin(g_virtual_tp_calc_1, g_virtual_tp_calc_2); // 原global_53_do
                g_virtual_tp_price = (g_min_real_level >= g_max_martin_steps) ? g_virtual_tp_calc_1 : g_virtual_tp_price; // 原global_53_do
            }
            else
            {
                g_virtual_tp_price = g_virtual_tp_calc_2; // 原global_53_do = global_92_do
            }
            
            if (!UseVirtualTP)
            {
                ModifyTakeProfit(1, g_current_magic, g_virtual_tp_price); // 原lizongs4
            }
            else
            {
                ModifyTakeProfit(1, g_current_magic, 0.0); // 原lizongs4
            }
            
            GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "tp", g_virtual_tp_price); // 原GlobalVariableSet
            
            double peak_price = GlobalVariableGet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak"); // 原local_12_do
            if ((iHigh(g_current_symbol, 0, 1) > peak_price || peak_price == 0.0)) // 原(iHigh(global_50_st, 0, 1) > local_12_do || local_12_do == 0.0)
            {
                peak_price = iHigh(g_current_symbol, 0, 1); // 原local_12_do = iHigh(global_50_st, 0, 1)
                GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "peak", peak_price); // 原GlobalVariableSet
            }
            
            double symbol_bid = SymbolInfoDouble(g_current_symbol, SYMBOL_BID); // 原local_13_do = SymbolInfoDouble(global_50_st, 1)
            if (!(symbol_bid > 0.0)) // 原!(local_13_do > 0.0)
                continue;
                
            double spread_points = ((SymbolInfoDouble(g_current_symbol, SYMBOL_ASK) - symbol_bid) / symbol_bid) * 100000.0; // 原local_14_do = ((SymbolInfoDouble(global_50_st, 4) - local_13_do) / local_13_do) * 100000.0
            if (!((peak_price - g_lower_band) != 0.0) || !(spread_points < 50.0) || !((peak_price - g_upper_band) / (peak_price - g_lower_band) > g_unlock_percent)) // 原!((local_12_do - global_56_do) != 0.0) || !(local_14_do < 50.0) || !((local_12_do - global_127_do) / (local_12_do - global_56_do) > global_32_do)
                continue;
                
            if (UseUnloss)
            {
                if ((!(GetPositionVolume(g_current_symbol, 1, g_current_magic) > 0.0) || !UseUnloss)) // 原(!(lizongs3(global_50_st, 1, global_25_in) > 0.0) || !(UseUnloss))
                    continue;
            }
            
            ClosePositions(g_current_symbol, -1, g_current_magic); // 原lizong_17
            if (CheckPositionExists(g_current_symbol, -1, g_current_magic, 0, "")) // 原lizongs2(global_50_st, -1, global_25_in, 0, "")
                continue;
                
            GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + "1" + IntegerToString(g_virtual_magic), 0.0);
            GlobalVariableSet(IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic), 0.0);
        }
    }
    
    if (!g_enable_visual_mode) // 原!(global_6_bo)
        return;
        
    if ((MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_VISUAL_MODE))) // 原(MQLInfoInteger(MQL_TESTER) && !(IsVisualMode()))
        return;
        
    UpdateInterfaceDisplay(); // 原lizong_27
}

//+------------------------------------------------------------------+
//| 定时器事件 (原OnTimer)
//+------------------------------------------------------------------+
void OnTimer()
{
    // 原MQL4: if (IsTesting()) return;
    if (MQLInfoInteger(MQL_TESTER))
        return;
        
    // 原MQL4: lizong_27();
    UpdateInterfaceDisplay();
}

//+------------------------------------------------------------------+
//| 清理函数 (原deinit)
//+------------------------------------------------------------------+
int OnDeinit(const int reason)
{
    // 原MQL4: if (IsTesting() && global_47_bo)
    if (MQLInfoInteger(MQL_TESTER) && g_enable_test_mode)
    {
        SaveEquityData(); // 原lizong_22
    }
    
    // 原MQL4: if (IsTesting() && global_48_bo)
    if (MQLInfoInteger(MQL_TESTER) && g_enable_visual_mode)
    {
        SaveOrderHistory(); // 原lizong_21
    }
    
    // 遍历所有符号
    for (int i = 0; i < g_symbol_count; i++)
    {
        g_current_symbol = g_symbol_list[i];
        
        // 遍历所有策略
        for (int j = 1; j <= g_max_strategies; j++)
        {
            // 严格按照MQL4 deinit的逻辑重新计算虚拟魔术号
            string strategy_num_str = IntegerToString(j, 2, '0');
            string symbol_code = CalculateSymbolCode(g_current_symbol);
            int virtual_magic = (int)StringToInteger(symbol_code + strategy_num_str);
            
            // 如果在测试模式下，删除所有全局变量 (确保与OnTick中所有Set操作完全对应)
            if (MQLInfoInteger(MQL_TESTER))
            {
                string tester_prefix = IntegerToString((int)MQLInfoInteger(MQL_TESTER));
                GlobalVariableDel(tester_prefix + "NUMBER" + g_current_symbol + IntegerToString(virtual_magic));
                GlobalVariableDel(tester_prefix + "Distance_Price" + g_current_symbol + IntegerToString(virtual_magic));
                GlobalVariableDel(tester_prefix + g_current_symbol + IntegerToString(virtual_magic) + "peak");
                GlobalVariableDel(tester_prefix + "Magic" + g_current_symbol + IntegerToString(virtual_magic));
                GlobalVariableDel(tester_prefix + g_current_symbol + IntegerToString(virtual_magic) + "tp");
                GlobalVariableDel(tester_prefix + g_current_symbol + "0" + IntegerToString(virtual_magic));
                GlobalVariableDel(tester_prefix + g_current_symbol + "1" + IntegerToString(virtual_magic));
            }
        }
    }
    
    return 0;
}

//+------------------------------------------------------------------+
//| 保存订单历史 (原lizong_21函数)
//+------------------------------------------------------------------+
void SaveOrderHistory()
{
    string order_type_str = "";
    string profit_str = "";
    string swap_str = "";
    string commission_str = "";
    string lots_str = "";
    string open_price_str = "";
    string close_price_str = "";
    string sl_str = "";
    string tp_str = "";
    int digits = 0;
    
    // 构建文件名
    string filename = MQLInfoString(MQL_PROGRAM_NAME) + " orders " + g_current_symbol + " " + 
                     IntegerToString(g_max_strategies) + "-" + DoubleToString(g_virtual_tp_coeff3) + "-" + 
                     IntegerToString(g_delay_time_1) + "-" + IntegerToString(g_delay_time_2) + "-" + 
                     DoubleToString(g_virtual_tp_coeff1) + "-" + DoubleToString(g_virtual_tp_coeff2) + "-" + 
                     IntegerToString(g_unlock_percent) + "-" + DoubleToString(g_tp_price_coefficient) + ".csv";
                     
    // 删除旧文件
    string filepath = "Report " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "//" + filename;
    FileDelete(filepath);
    
    // 打开文件
    int file_handle = FileOpen(filepath, FILE_WRITE|FILE_CSV);
    if (file_handle == INVALID_HANDLE)
    {
        PrintFormat("Error opening file");
        return;
    }
    
    // 写入表头
    FileWrite(file_handle, "Run", "Order Ticket", "Order Type", "Lots", "Symbol", "Open Price", 
              "Close Price", "Stop Loss", "Take Profit", "Open Time", "Close Time", 
              "Magic Number", "Profit", "Swap", "Commission", "Comment", "Analytics");
              
    // 移动到文件末尾
    FileSeek(file_handle, 0, SEEK_END);
    
    // 遍历历史订单
    HistorySelect(0, TimeCurrent());
    for (int i = 0; i < HistoryDealsTotal(); i++)
    {
        ulong ticket = HistoryDealGetTicket(i);
        if (ticket == 0) continue;
        
        // 获取订单信息
        digits = (int)SymbolInfoInteger(HistoryDealGetString(ticket, DEAL_SYMBOL), SYMBOL_DIGITS);
        profit_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_PROFIT), 2);
        swap_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_SWAP), 2);
        commission_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_COMMISSION), 2);
        lots_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_VOLUME), 2);
        open_price_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_PRICE), digits);
        close_price_str = DoubleToString(HistoryDealGetDouble(ticket, DEAL_PRICE), digits);
        sl_str = DoubleToString(0, digits); // MQL5中需要额外处理SL/TP
        tp_str = DoubleToString(0, digits); // MQL5中需要额外处理SL/TP
        
        // 获取订单类型字符串
        ENUM_DEAL_TYPE deal_type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(ticket, DEAL_TYPE);
        switch(deal_type)
        {
            case DEAL_TYPE_BUY: order_type_str = "BUY"; break;
            case DEAL_TYPE_SELL: order_type_str = "SELL"; break;
            default: order_type_str = "OTHER"; break;
        }
        
        // 写入订单数据
        FileWrite(file_handle, 
            filename,
            IntegerToString(ticket),
            order_type_str,
            lots_str,
            HistoryDealGetString(ticket, DEAL_SYMBOL),
            open_price_str,
            close_price_str,
            sl_str,
            tp_str,
            TimeToString((datetime)HistoryDealGetInteger(ticket, DEAL_TIME), TIME_DATE|TIME_SECONDS),
            TimeToString((datetime)HistoryDealGetInteger(ticket, DEAL_TIME), TIME_DATE|TIME_SECONDS),
            HistoryDealGetInteger(ticket, DEAL_MAGIC),
            profit_str,
            swap_str,
            commission_str,
            HistoryDealGetString(ticket, DEAL_COMMENT),
            "0" // Analytics placeholder
        );
    }
    
    FileClose(file_handle);
}

//+------------------------------------------------------------------+
//| 保存净值数据 (原lizong_22函数)
//+------------------------------------------------------------------+
void SaveEquityData()
{
    // 构建文件名
    string filename = MQLInfoString(MQL_PROGRAM_NAME) + " equity " + g_current_symbol + " " + 
                     IntegerToString(g_max_strategies) + "-" + DoubleToString(g_virtual_tp_coeff3) + "-" + 
                     IntegerToString(g_delay_time_1) + "-" + IntegerToString(g_delay_time_2) + "-" + 
                     DoubleToString(g_virtual_tp_coeff1) + "-" + DoubleToString(g_virtual_tp_coeff2) + "-" + 
                     IntegerToString(g_unlock_percent) + "-" + DoubleToString(g_tp_price_coefficient) + ".csv";
                     
    // 删除旧文件
    string filepath = "Report " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "//" + filename;
    FileDelete(filepath);
    
    // 打开文件
    int file_handle = FileOpen(filepath, FILE_WRITE|FILE_CSV);
    if (file_handle == INVALID_HANDLE)
    {
        PrintFormat("Error opening file");
        return;
    }
    
    // 写入表头
    FileWrite(file_handle, "Run", "Symbol", "Date", "Balance", "Equity", "Min Equity", "Symbol Coef", "Margin", "Max Margin");
    
    // 移动到文件末尾
    FileSeek(file_handle, 0, SEEK_END);
    
    // 写入测试数据
    for (int i = 0; i < g_array_index_2; i++)
    {
        FileWrite(file_handle,
            filename,
            g_current_symbol,
            TimeToString((datetime)g_test_data[0][i], TIME_DATE|TIME_SECONDS),
            (int)g_test_data[1][i],  // Balance
            (int)g_test_data[2][i],  // Equity
            (int)g_test_data[3][i],  // Min Equity
            (int)g_test_data[5][i],  // Symbol Coefficient
            (int)g_test_data[6][i]   // Margin
        );
    }
    
    FileClose(file_handle);
}

//+------------------------------------------------------------------+
//| 交易信号分析
//+------------------------------------------------------------------+
int AnalyzeTradingSignal()
{
    // 更新市场信息
    g_symbol.RefreshRates();
    
    // 计算指标
    CalculateIndicators();
    
    // 获取交易信号
    return GetTradingSignal();
}

//+------------------------------------------------------------------+
//| 指标计算 (原lizong_13函数)
//+------------------------------------------------------------------+
void CalculateIndicators()
{
    // 获取指标句柄
    static int ma_handle = INVALID_HANDLE;
    static int stddev_handle = INVALID_HANDLE;
    
    // 初始化指标句柄
    if(ma_handle == INVALID_HANDLE) {
        ma_handle = iMA(g_current_symbol, PERIOD_CURRENT, g_ma_period, 0, MODE_SMA, PRICE_CLOSE);
        if(ma_handle == INVALID_HANDLE) {
            Print("Error: Failed to create MA indicator handle");
            return;
        }
    }
    
    if(stddev_handle == INVALID_HANDLE) {
        stddev_handle = iStdDev(g_current_symbol, PERIOD_CURRENT, g_ma_period, 0, MODE_SMA, PRICE_CLOSE);
        if(stddev_handle == INVALID_HANDLE) {
            Print("Error: Failed to create StdDev indicator handle");
            return;
        }
    }
    
    // 获取指标数据
    double ma_buffer[];
    double stddev_buffer[];
    ArraySetAsSeries(ma_buffer, true);
    ArraySetAsSeries(stddev_buffer, true);
    
    // 复制最新的指标数据
    if(!CopyBuffer(ma_handle, 0, 0, 1, ma_buffer) || 
       !CopyBuffer(stddev_handle, 0, 0, 1, stddev_buffer)) {
        Print("Error: Failed to copy indicator buffers");
        return;
    }
    
    // 计算指标值
    g_ma_value = ma_buffer[0];
    double base_stddev = stddev_buffer[0];
    g_stddev_value = base_stddev * g_stddev_multiplier;
    

    
    // 原MQL4: if (global_24_bo == true) { double local_1_do = lizongs11(global_14_in, global_18_in); if (local_1_do > 0.0) { global_58_do = MathMax(global_58_do, local_1_do); } }
    if (g_use_dynamic_stddev)
    {
        double dynamic_stddev = CalculateDynamicStdDev(g_grid_level, g_ma_period);
        if (dynamic_stddev > 0.0)
        {
            g_stddev_value = MathMax(g_stddev_value, dynamic_stddev);
        }
    }
    
    // 原MQL4: global_55_do = global_56_do + global_58_do;
    g_upper_band = g_ma_value + g_stddev_value;
    

    
    // 原MQL4: global_57_do = global_56_do - global_58_do;
    g_lower_band = g_ma_value - g_stddev_value;
    
    // 原MQL4: global_52_in = global_27_in;
    // 注意：这里不需要额外的变量，因为g_strategy_index已经存在
}

//+------------------------------------------------------------------+
//| 订单修改
//+------------------------------------------------------------------+
void ModifyOrder(double open_price, double stop_loss, double take_profit, datetime expiration)
{
    // 原MQL4: lizong_14(double para_0_do, double para_1_do, double para_2_do, datetime para_3_拆da)
    bool modify_success = false;
    double current_open_price, current_stop_loss, current_take_profit;
    double new_open_price, new_stop_loss, new_take_profit;
    int digits;
    int retry_count;
    int error_code;
    double ask_price, bid_price;
    string author_string;
    
    // 原MQL4: 初始化变量
    author_string = " 作者函数: ";
    retry_count = 0;
    error_code = 0;
    
    // 原MQL4: int local_7_in = MarketInfo(OrderSymbol(), 12);
    digits = (int)SymbolInfoInteger(g_current_symbol, SYMBOL_DIGITS);
    
    // 原MQL4: 获取当前订单信息
    if (open_price <= 0.0)
    {
        open_price = PositionGetDouble(POSITION_PRICE_OPEN);
    }
    if (stop_loss < 0.0)
    {
        stop_loss = PositionGetDouble(POSITION_SL);
    }
    if (take_profit < 0.0)
    {
        take_profit = PositionGetDouble(POSITION_TP);
    }
    
    // 原MQL4: 规范化价格
    new_open_price = NormalizeDouble(open_price, digits);
    new_stop_loss = NormalizeDouble(stop_loss, digits);
    new_take_profit = NormalizeDouble(take_profit, digits);
    
    // 原MQL4: 获取当前订单价格
    current_open_price = NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN), digits);
    current_stop_loss = NormalizeDouble(PositionGetDouble(POSITION_SL), digits);
    current_take_profit = NormalizeDouble(PositionGetDouble(POSITION_TP), digits);
    
    // 原MQL4: 检查是否需要修改
    if (!(new_open_price != current_open_price) && !(new_stop_loss != current_stop_loss) && !(new_take_profit != current_take_profit))
    {
        return;
    }
    
    // 原MQL4: 重试循环
    for (retry_count = 1; retry_count <= 5; retry_count++)
    {
        // 原MQL4: 检查交易状态
        if (!MQLInfoInteger(MQL_TESTER) && (!MQLInfoInteger(MQL_TRADE_ALLOWED) || MQLInfoInteger(MQL_TRADE_ALLOWED) == 0))
        {
            return;
        }
        
        // 原MQL4: RefreshRates();
        // MQL5中RefreshRates()已被移除，使用SymbolInfoTick()来刷新价格
        MqlTick last_tick;
        SymbolInfoTick(g_current_symbol, last_tick);
        
        // 原MQL4: 修改订单
        // 注意：MQL5中需要先选择持仓，然后修改
        if (PositionSelectByTicket(PositionGetTicket(0))) // 假设修改第一个持仓
        {
            modify_success = g_trade.PositionModify(PositionGetTicket(0), new_stop_loss, new_take_profit);
        }
        
        if (modify_success)
        {
            return;
        }
        
        // 原MQL4: 获取错误信息
        error_code = GetLastError();
        ask_price = SymbolInfoDouble(g_current_symbol, SYMBOL_ASK);
        bid_price = SymbolInfoDouble(g_current_symbol, SYMBOL_BID);
        
        // 原MQL4: 打印错误信息
        PrintFormat("Error(" + IntegerToString(error_code) + ") modifying order: " + GetErrorDescription(error_code) + ", try " + IntegerToString(retry_count));
        PrintFormat("Ask=" + DoubleToString(ask_price, digits) + "  Bid=" + DoubleToString(bid_price, digits) + "  sy=" + g_current_symbol + "  op=" + DoubleToString(new_open_price, digits) + "  sl=" + DoubleToString(new_stop_loss, digits) + "  tp=" + DoubleToString(new_take_profit, digits));
        
        // 原MQL4: 处理交易上下文繁忙错误
        if (error_code == 146) // ERR_TRADE_CONTEXT_BUSY
        {
            // MQL5中IsTradeContextBusy()已被移除，使用Sleep等待
            Sleep(500);
        }
    }
}

//+------------------------------------------------------------------+
//| 开买单 (严格遵循MQL4 lizong_15 的参数和逻辑)
//+------------------------------------------------------------------+
int ExecuteBuyOrder(double lot, string comment)
{
    g_trade.SetExpertMagicNumber(g_current_magic);
    g_trade.SetDeviationInPoints(0); // MQL4中 global_15_in 从未被赋值，默认为0，即不允许滑点

    if (g_trade.Buy(lot, g_current_symbol, 0, 0, 0, comment))
    {
        return (int)g_trade.ResultOrder();
    }
    
    return -1;
}

//+------------------------------------------------------------------+
//| 开卖单 (严格遵循MQL4 lizong_15 的参数和逻辑)
//+------------------------------------------------------------------+
int ExecuteSellOrder(double lot, string comment)
{
    g_trade.SetExpertMagicNumber(g_current_magic);
    g_trade.SetDeviationInPoints(0); // MQL4中 global_15_in 从未被赋值，默认为0，即不允许滑点

    if (g_trade.Sell(lot, g_current_symbol, 0, 0, 0, comment))
    {
        return (int)g_trade.ResultOrder();
    }
    
    return -1;
}

//+------------------------------------------------------------------+
//| 平仓
//+------------------------------------------------------------------+
void ClosePositions(string symbol, int type, int magic)
{
    string check_symbol = symbol;
    if (symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && PositionGetInteger(POSITION_TYPE) != type))
            continue;
            
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL))
            continue;
            
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic))
            continue;
            
        // 获取当前价格
        g_symbol.RefreshRates();
        double close_price;
        if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            close_price = g_symbol.Bid();
        else
            close_price = g_symbol.Ask();
            
        // 尝试平仓，最多20次
        for (int try_count = 1; try_count <= 20; try_count++)
        {
            if (g_trade.PositionClose(PositionGetTicket(i)))
                break;
                
            Print("Error(", g_trade.ResultRetcode(), ") closing position: ", GetErrorDescription(g_trade.ResultRetcode()), ", try ", try_count);
            
            // 如果是交易上下文忙，等待
            if (g_trade.ResultRetcode() == TRADE_RETCODE_TRADE_DISABLED || g_trade.ResultRetcode() == TRADE_RETCODE_CONNECTION)
                Sleep(500);
                
            g_symbol.RefreshRates();
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                close_price = g_symbol.Bid();
            else
                close_price = g_symbol.Ask();
        }
    }
}

//+------------------------------------------------------------------+
//| 转换货币符号为数字 (原lizong_20函数)
//+------------------------------------------------------------------+
string ConvertSymbolToNumber(string symbol_part)
{
    // 原MQL4: lizong_20(string para_0_st)
    if (StringLen(symbol_part) != 3)
        return "9";
    
    if (symbol_part == "AUD")
        return "1";
    if (symbol_part == "CAD")
        return "2";
    if (symbol_part == "EUR")
        return "3";
    if (symbol_part == "GBP")
        return "4";
    if (symbol_part == "JPY")
        return "5";
    if (symbol_part == "NZD")
        return "6";
    if (symbol_part == "USD")
        return "7";
    
    return "9";
}

//+------------------------------------------------------------------+
//| 计算品种代码 (原zs1函数)
//+------------------------------------------------------------------+
string CalculateSymbolCode(string symbol)
{
    // 移除可能的后缀（如GBPUSDm中的m）
    string clean_symbol = symbol;
    if (StringLen(symbol) > 6)
        clean_symbol = StringSubstr(symbol, 0, 6);
        
    if (StringLen(clean_symbol) != 6)
        return "99";
        
    string first_part = StringSubstr(clean_symbol, 0, 3);   // 前三个字符
    string second_part = StringSubstr(clean_symbol, 3, 3);  // 后三个字符
    
    return ConvertSymbolToNumber(first_part) + ConvertSymbolToNumber(second_part);
}

//+------------------------------------------------------------------+
//| 获取错误描述 (原lizong_18函数)
//+------------------------------------------------------------------+
string GetErrorDescription(int error_code)
{
    // 原MQL4: lizong_18(int para_0_in)
    switch (error_code)
    {
    case 0:
    case 1:
        return "no error";
    case 2:
        return "common error";
    case 3:
        return "invalid trade parameters";
    case 4:
        return "trade server is busy";
    case 5:
        return "old version of the client terminal";
    case 6:
        return "no connection with trade server";
    case 7:
        return "not enough rights";
    case 8:
        return "too frequent requests";
    case 9:
        return "malfunctional trade operation (never returned error)";
    case 64:
        return "account disabled";
    case 65:
        return "invalid account";
    case 128:
        return "trade timeout";
    case 129:
        return "invalid price";
    case 130:
        return "invalid stops";
    case 131:
        return "invalid trade volume";
    case 132:
        return "market is closed";
    case 133:
        return "trade is disabled";
    case 134:
        return "not enough money";
    case 135:
        return "price changed";
    case 136:
        return "off quotes";
    case 137:
        return "broker is busy (never returned error)";
    case 138:
        return "requote";
    case 139:
        return "order is locked";
    case 140:
        return "long positions only allowed";
    case 141:
        return "too many requests";
    case 145:
        return "modification denied because order too close to market";
    case 146:
        return "trade context is busy";
    case 147:
        return "expirations are denied by broker";
    case 148:
        return "amount of open and pending orders has reached the limit";
    case 149:
        return "hedging is prohibited";
    case 150:
        return "prohibited by FIFO rules";
    default:
        return "unknown error";
    }
}
//+------------------------------------------------------------------+
//| 网格交易逻辑
//+------------------------------------------------------------------+
int ExecuteGridStrategy()
{
    g_grid_distance = GlobalVariableGet(
        IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + 
        "Distance_Price" + g_current_symbol + 
        IntegerToString(g_virtual_magic)
    );
    // Print("ExecuteGridStrategy",g_grid_distance);
    // 局部变量声明
    double lot_size = 0.0;
    bool is_executed = false;
    int order_ticket = 0;

    
    // 检查网格距离是否为0并计算 (原MQ4: if (global_69_do == 0.0))
    if (g_grid_distance == 0.0)
    {
        // 买单持仓检查 (原MQ4: lizongs2(global_50_st, 0, global_25_in, 0, ""))
        bool has_buy = CheckPositionExists(g_current_symbol, POSITION_TYPE_BUY, g_current_magic, 0, "");
        
        if (has_buy)
        {
            // 计算网格距离 (原MQ4: global_70_in = (global_55_do - global_56_do) / global_128_do)
            g_temp_grid_distance = (g_upper_band - g_ma_value) / g_symbol_point;
            
            // 设置网格距离 (原MQ4: global_69_do = (global_129_do - global_70_in) * global_128_do + MathMin(iClose(global_50_st, 0, 1), global_127_do))
            g_grid_distance = (g_symbol.Ask() - g_temp_grid_distance * g_symbol_point) + MathMin(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol.Bid());
            
            // 保存到全局变量并更新界面 (原MQ4: GlobalVariableSet + lizongs7)
            GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "Distance_Price" + g_current_symbol + IntegerToString(g_virtual_magic), g_grid_distance);
            UpdateInterface();
        }
        
        // 卖单持仓检查 (原MQ4: lizongs2(global_50_st, 1, global_25_in, 0, ""))
        bool has_sell = CheckPositionExists(g_current_symbol, POSITION_TYPE_SELL, g_current_magic, 0, "");
        
        if (has_sell)
        {
            // 计算网格距离 (原MQ4: global_70_in = (global_55_do - global_56_do) / global_128_do)
            g_temp_grid_distance = (g_upper_band - g_ma_value) / g_symbol_point;
            
            // 设置网格距离 (原MQ4: global_69_do = global_70_in * global_128_do + MathMax(iClose(global_50_st, 0, 1), global_127_do))
            g_grid_distance = g_temp_grid_distance * g_symbol_point + MathMax(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol.Ask());
            
            // 保存到全局变量并更新界面 (原MQ4: GlobalVariableSet + lizongs7)
            GlobalVariableSet(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "Distance_Price" + g_current_symbol + IntegerToString(g_virtual_magic), g_grid_distance);
            UpdateInterface();
        }
    }
    
    // 初始化网格编号
    if (!GlobalVariableCheck(IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic)))
    {
        SetVirtualOrderNumber(g_current_symbol, -1, g_current_magic);
    }
    
    // 更新市场信息
    g_symbol.RefreshRates();
    double spread = g_symbol.Ask() - g_symbol.Bid();
    double volatility = 0.0;
    
    if (iClose(g_current_symbol, PERIOD_CURRENT, 1) > 0.0)
    {
        volatility = (MathAbs(g_symbol.Ask() / iClose(g_current_symbol, PERIOD_CURRENT, 1) - 1.0)) * 10000.0;
    }
    
    // Print("Grid Strategy Status - Symbol:", g_current_symbol,
    //   ", Signal:", g_trading_signal,
    //   ", Grid Distance:", g_grid_distance,
    //   ", Bid:", g_symbol_bid,
    //   ", Ask:", g_symbol_ask,
    //   ", Grid Level:", g_grid_level,
    //   ", MA Value:", g_ma_value,
    //   ", Upper Band:", g_upper_band,
    //   ", Lower Band:", g_lower_band,
    //   ", Martin Coef:", g_martin_coefficient,
    //   ", Grid Points:", (g_upper_band - g_ma_value) / g_symbol_point);
    // 网格交易逻辑
    if (g_grid_distance != 0.0)
    {
    //     Print("Grid Strategy Status - Symbol:", g_current_symbol,
    //   ", Signal:", g_trading_signal,
    //   ", Grid Distance:", g_grid_distance,
    //   ", Bid:", g_symbol_bid,
    //   ", Ask:", g_symbol_ask,
    //   ", Grid Level:", g_grid_level,
    //   ", MA Value:", g_ma_value,
    //   ", Upper Band:", g_upper_band,
    //   ", Lower Band:", g_lower_band,
    //   ", Martin Coef:", g_martin_coefficient,
    //   ", Grid Points:", (g_upper_band - g_ma_value) / g_symbol_point);
        if (DELAYtime(g_current_symbol, -1, g_current_magic, "HS", iTime(g_current_symbol, PERIOD_CURRENT, 0)) > g_ma_period * g_virtual_tp_coeff3 * PeriodSeconds(PERIOD_CURRENT) && volatility < 20.0)
        {
            // 买入网格逻辑
            if (CheckPositionExists(g_current_symbol, POSITION_TYPE_BUY, g_current_magic, 0, "") || CheckVirtualTakeProfit(POSITION_TYPE_BUY))
            {
                // 原MQ4: if (global_126_do <= global_69_do) -> MQL5应该是Ask价
                if (g_symbol.Ask() <= g_grid_distance)
                {
                    is_executed = false;
                    lot_size = NormalizeDouble(CalculateLotSize(1.0, false) * MathPow(g_martin_coefficient, MathMin(g_max_martin_steps, g_grid_level + 1)), 2);
                    
                    if (FirstNumber > g_grid_level + 1 || (g_min_real_level < g_grid_level + 1 && g_min_real_level > 0))
                    {
                        SetGlobalVar("", "0", 1.0);
                        is_executed = true;
                        order_ticket = -1;
                        Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " [strategy buy] The opened grid level is less than the minimum level. The deal is virtualized");
                    }
                    else if (lot_size < SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN))
                    {
                        SetGlobalVar("", "0", 1.0);
                        is_executed = true;
                        order_ticket = -1;
                        Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " Current lot < min_lot. The average deal is virtualized");
                    }
                    else
                    {
                        order_ticket = ExecuteBuyOrder(lot_size, "C" + IntegerToString(g_grid_level + 1));
                        if (order_ticket > 0) {
                            SetGlobalVar("", "0", 0.0);
                            is_executed = true;
                        }
                    }
                    
                    if (is_executed)
                    {
                        int old_grid_level = g_grid_level;
                        g_grid_level++;
                        PrintFormat("[GridLevel-Increase] Magic:%d, From:%d, To:%d", g_virtual_magic, old_grid_level, g_grid_level);
                        UpdateVirtualOrder(order_ticket);
                        SetGlobalVar("NUMBER", "", g_grid_level);
                        int grid_points = (int)((g_upper_band - g_ma_value) / g_symbol.Point());
                        g_grid_distance = MathMin(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol.Bid()) + (g_symbol.Ask() - g_symbol.Bid() - grid_points * g_symbol.Point());
                        SetGlobalVar("Distance_Price", "", g_grid_distance);
                        UpdateInterface();
                    }
                }
            }
            // 卖出网格逻辑
            else if (CheckPositionExists(g_current_symbol, POSITION_TYPE_SELL, g_current_magic, 0, "") || CheckVirtualTakeProfit(POSITION_TYPE_SELL))
            {
                // 原MQ4: if (global_127_do >= global_69_do) -> MQL5应该是Bid价
                if (g_symbol.Bid() >= g_grid_distance)
                {
                    is_executed = false;
                    lot_size = NormalizeDouble(CalculateLotSize(1.0, false) * MathPow(g_martin_coefficient, MathMin(g_max_martin_steps, g_grid_level + 1)), 2);
                    
                    if (FirstNumber > g_grid_level + 1 || (g_min_real_level < g_grid_level + 1 && g_min_real_level > 0))
                    {
                        SetGlobalVar("", "1", 1.0);
                        is_executed = true;
                        order_ticket = -1;
                        Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " [strategy sell] The opened grid level is less than the minimum level. The deal is virtualized");
                    }
                    else if (lot_size < SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN))
                    {
                        SetGlobalVar("", "1", 1.0);
                        is_executed = true;
                        order_ticket = -1;
                        Print(g_current_symbol + " " + IntegerToString(g_current_magic) + " Current lot < min_lot. The average deal is virtualized");
                    }
                    else
                    {
                        order_ticket = ExecuteSellOrder(lot_size, "C" + IntegerToString(g_grid_level + 1));
                         if (order_ticket > 0) {
                            SetGlobalVar("", "1", 0.0);
                            is_executed = true;
                        }
                    }

                    if (is_executed)
                    {
                        int old_grid_level = g_grid_level;
                        g_grid_level++;
                        PrintFormat("[GridLevel-Increase] Magic:%d, From:%d, To:%d", g_virtual_magic, old_grid_level, g_grid_level);
                        UpdateVirtualOrder(order_ticket);
                        SetGlobalVar("NUMBER", "", g_grid_level);
                        int grid_points = (int)((g_upper_band - g_ma_value) / g_symbol.Point());
                        g_grid_distance = grid_points * g_symbol.Point() + MathMax(iClose(g_current_symbol, PERIOD_CURRENT, 1), g_symbol.Ask());
                        SetGlobalVar("Distance_Price", "", g_grid_distance);
                        UpdateInterface();
                    }
                }
            }
        }
    }
    
    return 0;
}

//+------------------------------------------------------------------+
//| 加载策略配置
//+------------------------------------------------------------------+
void LoadStrategyConfigs(string symbol, S_StrategyConfig &configs[])
{
    // 策略配置加载逻辑已实现在LoadCustomStrategyConfigs中
}

//+------------------------------------------------------------------+
//| 初始化动态标准差参数 (原lizong_24函数)
//+------------------------------------------------------------------+
void InitializeDynamicStdDevParams()
{
    // 原MQL4: global_122_do_si6si5si2[0][0][0] = 0.0000897; 等等
    // 这里设置一个简化的三维数组，包含动态标准差参数
    g_3d_array[0][0][0] = 0.0000897;
    g_3d_array[0][1][0] = 0.0001034;
    g_3d_array[0][2][0] = 0.0001795;
    g_3d_array[0][3][0] = 0.0002647;
    g_3d_array[0][4][0] = 0.0002584;
    g_3d_array[1][0][0] = 0.0000588;
    g_3d_array[1][1][0] = 0.0000813;
    g_3d_array[1][2][0] = 0.0001579;
    g_3d_array[1][3][0] = 0.0003007;
    g_3d_array[1][4][0] = 0.0004076;
    g_3d_array[2][0][0] = 0.0000738;
    g_3d_array[2][1][0] = 0.0000939;
    g_3d_array[2][2][0] = 0.0001887;
    g_3d_array[2][3][0] = 0.0003237;
    g_3d_array[2][4][0] = 0.0003535;
    g_3d_array[3][0][0] = 0.0000645;
    g_3d_array[3][1][0] = 0.0000914;
    g_3d_array[3][2][0] = 0.000148;
    g_3d_array[3][3][0] = 0.0002208;
    g_3d_array[3][4][0] = 0.00025;
    g_3d_array[4][0][0] = 0.000054;
    g_3d_array[4][1][0] = 0.0000639;
    g_3d_array[4][2][0] = 0.0000964;
    g_3d_array[4][3][0] = 0.0001486;
    g_3d_array[4][4][0] = 0.0001765;
    g_3d_array[5][0][0] = 0.000258;
    g_3d_array[5][1][0] = 0.000221;
    g_3d_array[5][2][0] = 0.000159;
    g_3d_array[5][3][0] = 0.000221;
    g_3d_array[5][4][0] = 0.000258;
    
    // 第二维数据
    g_3d_array[0][0][1] = 0.5292458;
    g_3d_array[0][1][1] = 0.5154581;
    g_3d_array[0][2][1] = 0.4603964;
    g_3d_array[0][3][1] = 0.4371622;
    g_3d_array[0][4][1] = 0.4761835;
    g_3d_array[1][0][1] = 0.5749035;
    g_3d_array[1][1][1] = 0.5317178;
    g_3d_array[1][2][1] = 0.4514056;
    g_3d_array[1][3][1] = 0.3911576;
    g_3d_array[1][4][1] = 0.3704194;
    g_3d_array[2][0][1] = 0.5909246;
    g_3d_array[2][1][1] = 0.5569647;
    g_3d_array[2][2][1] = 0.475178;
    g_3d_array[2][3][1] = 0.4380521;
    g_3d_array[2][4][1] = 0.4670035;
    g_3d_array[3][0][1] = 0.5916496;
    g_3d_array[3][1][1] = 0.5410278;
    g_3d_array[3][2][1] = 0.4918849;
    g_3d_array[3][3][1] = 0.461836;
    g_3d_array[3][4][1] = 0.49;
    g_3d_array[4][0][1] = 0.5956147;
    g_3d_array[4][1][1] = 0.5731626;
    g_3d_array[4][2][1] = 0.538971;
    g_3d_array[4][3][1] = 0.513383;
    g_3d_array[4][4][1] = 0.5309254;
    g_3d_array[5][0][1] = 0.476184;
    g_3d_array[5][1][1] = 0.461836;
    g_3d_array[5][2][1] = 0.479234;
    g_3d_array[5][3][1] = 0.461836;
    g_3d_array[5][4][1] = 0.476184;
}

//+------------------------------------------------------------------+
//| 初始化策略参数 (原lizong_26函数)
//+------------------------------------------------------------------+
void InitializeStrategyParams()
{
    // 创建基础UI框架
    InitializeInterfaceDisplay();
    
    // 初始化全局变量
    g_martin_coefficient = LotsMartinRatio;
    g_ma_period = g_delay_time_1;
    
    // 如果不是默认策略或有自定义设置
    if (g_strategy_type != 1 || TrimString(g_empty_string) != "")
    {
        // 使用策略配置
        for (int i = 0; i < g_max_strategies; i++)
        {
            g_ma_period = g_strategy_configs[i].parameter_1;
            g_stddev_multiplier = g_strategy_configs[i].parameter_2;
            g_virtual_tp_coeff1 = g_strategy_configs[i].parameter_3;
            g_virtual_tp_coeff2 = g_strategy_configs[i].parameter_4;
            g_unlock_percent = (int)g_strategy_configs[i].parameter_5;
            g_tp_price_coefficient = g_strategy_configs[i].parameter_6;
            g_virtual_tp_coeff3 = g_strategy_configs[i].parameter_7;
        }
    }
}

//+------------------------------------------------------------------+
//| 设置当前策略参数 (原lizong_29函数)
//+------------------------------------------------------------------+
void UpdateStrategyParameters(int strategy_index)
{
    // 严格按照MQL4的lizong_29逻辑，每次都重新计算魔术号
    string strategy_num_str = IntegerToString(strategy_index, 2, '0');
    string symbol_code = CalculateSymbolCode(g_current_symbol);
    string server_code = IntegerToString(ServerNumber, 2, '0');

    // 1. 重新计算虚拟魔术号 (用于全局变量键)
    g_virtual_magic = (int)StringToInteger(symbol_code + strategy_num_str);
    
    // 2. 重新计算真实魔术号 (用于交易)
    g_current_magic = (int)StringToInteger(symbol_code + server_code + strategy_num_str);

    // 设置马丁系数
    g_martin_coefficient = LotsMartinRatio;
    
    // 设置移动平均周期
    g_ma_period = g_delay_time_1;
    
    // 如果不是默认策略或有自定义设置
    if (g_strategy_type != 1 || TrimString(g_empty_string) != "")
    {
        int config_index = strategy_index - 1;
        if(config_index >=0 && config_index < ArraySize(g_strategy_configs))
        {
            g_ma_period = g_strategy_configs[config_index].parameter_1;
            g_stddev_multiplier = g_strategy_configs[config_index].parameter_2;
            g_virtual_tp_coeff1 = g_strategy_configs[config_index].parameter_3;
            g_virtual_tp_coeff2 = g_strategy_configs[config_index].parameter_4;
            g_unlock_percent = (int)g_strategy_configs[config_index].parameter_5;
            g_tp_price_coefficient = g_strategy_configs[config_index].parameter_6;
            g_virtual_tp_coeff3 = g_strategy_configs[config_index].parameter_7;
        }
    }
    
    // 从全局变量加载网格级别
    string number_key = IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "NUMBER" + g_current_symbol + IntegerToString(g_virtual_magic);
    if(GlobalVariableCheck(number_key))
    {
        g_grid_level = (int)GlobalVariableGet(number_key);
    } 
    else 
    {
        g_grid_level = 0;
    }
    
    // 从全局变量加载网格距离价格
    string distance_key = IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + "Distance_Price" + g_current_symbol + IntegerToString(g_virtual_magic);
    if(GlobalVariableCheck(distance_key))
    {
        g_grid_distance = GlobalVariableGet(distance_key);
    }
    else
    {
        g_grid_distance = 0.0;
    }

    // 更新市场信息
    g_symbol.Name(g_current_symbol);
    g_symbol_point = g_symbol.Point();
    
    // 获取市场信息 (原MQL4: MarketInfo调用)
    // 注意：MQL4中的变量映射关系：
    // global_129_do = MarketInfo(13) = TICK_VALUE
    // global_125_do = MarketInfo(13) * MarketInfo(11) = 点差价值
    // global_126_do = MarketInfo(10) = SWAP_LONG (但在代码中也被用作ASK价格)
    // global_127_do = MarketInfo(9) = SWAP_SHORT (但在代码中也被用作BID价格)
    // global_128_do = MarketInfo(11) = POINT
    
    g_symbol_spread = g_symbol.TickValue();                                        // 原global_129_do = MarketInfo(13)
    g_point = g_symbol.TickValue() * g_symbol.Point();                            // 原global_125_do = MarketInfo(13) * MarketInfo(11)
    double swap_long = g_symbol.SwapLong();                                       // 原global_126_do = MarketInfo(10)
    double swap_short = g_symbol.SwapShort();                                     // 原global_127_do = MarketInfo(9)
    // g_symbol_point已在上面设置                                                 // 原global_128_do = MarketInfo(11)
    
    // 更新买卖价格
    g_symbol_bid = SymbolInfoDouble(g_current_symbol, SYMBOL_BID);
    g_symbol_ask = SymbolInfoDouble(g_current_symbol, SYMBOL_ASK);
    
    // 计算价格相对偏差 (原global_130_do)
    g_symbol_commission = 0.0;
    double prev_close = iClose(g_current_symbol, 0, 1);
    if (prev_close > 0.0)
    {
        g_symbol_commission = (MathAbs(g_symbol_bid / prev_close - 1.0)) * 10000.0;
    }

    // 计算指标
    CalculateIndicators();
    
    // ATR过滤检查 (原MQL4: 4214-4219行的逻辑)
    // 原MQL4: if (iATR(global_50_st, 1440, global_22_in, 1) / MarketInfo(global_50_st, 9) > global_23_do)
    double atr_value = iATR(g_current_symbol, PERIOD_D1, 14, 1);  // global_22_in = 14
    if(atr_value > 0 && g_symbol_bid > 0)
    {
        double atr_ratio = atr_value / g_symbol_bid;
        if(atr_ratio > 0.0143)  // global_23_do = 0.0143
        {
            g_enable_trading = false;  // 原global_123_bo = false
            return;
        }
    }
    g_enable_trading = true;  // 原global_123_bo = true
}

//+------------------------------------------------------------------+
//| 虚拟止盈处理
//+------------------------------------------------------------------+
void ProcessVirtualTakeProfit()
{
    // 原MQL4: lizong_30()
    double virtual_tp_price;
    
    // 原MQL4: local_1_do = GlobalVariableGet(string(MQLInfoInteger(MQL_TESTER)) + global_50_st + string(global_26_in) + "tp");
    string tp_key = IntegerToString((int)MQLInfoInteger(MQL_TESTER)) + g_current_symbol + IntegerToString(g_virtual_magic) + "tp";
    virtual_tp_price = GlobalVariableGet(tp_key);
    
    // 原MQL4: 检查买单虚拟止盈
    // if (lizongs2(global_50_st, 0, global_25_in, 0, "") && global_127_do >= local_1_do && local_1_do != 0.0)
    if (CheckPositionExists(g_current_symbol, 0, g_current_magic, 0, "") && 
        g_symbol_bid >= virtual_tp_price && virtual_tp_price != 0.0)
    {
        // 原MQL4: lizong_17(global_50_st, 0, global_25_in);
        ClosePositions(g_current_symbol, 0, g_current_magic);
    }
    
    // 原MQL4: 检查卖单虚拟止盈
    // if (!(lizongs2(global_50_st, 1, global_25_in, 0, "")) || !(global_126_do <= local_1_do))
    if (!CheckPositionExists(g_current_symbol, 1, g_current_magic, 0, "") || !(g_symbol.Ask() <= virtual_tp_price))
    {
        return;
    }
    
    // 原MQL4: lizong_17(global_50_st, 1, global_25_in);
    ClosePositions(g_current_symbol, 1, g_current_magic);
}

//+------------------------------------------------------------------+
//| 解析多货币字符串 (原xx函数)
//+------------------------------------------------------------------+
void ParseMultiCurrencyString(string input_string, string &symbols[])
{
    // 原MQL4: StringSplit(s2, StringGetCharacter(s1, 0), global_99_st_si11);
    StringSplit(input_string, StringGetCharacter(",", 0), symbols);
    
    int array_size = ArraySize(symbols);
    for (int i = 0; i < array_size; i++)
    {
        // 原MQL4: global_99_st_si11[tmp_in_2] = abc(global_99_st_si11[tmp_in_2]);
        symbols[i] = TrimString(symbols[i]);
    }
}

//+------------------------------------------------------------------+
//| 解析符号系数 (原xx1函数)
//+------------------------------------------------------------------+
void ParseSymbolCoefficients(string &symbols[], double &coefficients[])
{
    string separator = "*";
    ushort separator_char = StringGetCharacter(separator, 0);
    
    // 原MQL4: ArrayResize(global_100_do_si11, ArraySize(global_99_st_si11), 0);
    ArrayResize(coefficients, ArraySize(symbols), 0);
    
    for (int i = 0; i < ArraySize(symbols); i++)
    {
        string parts[2];
        // 原MQL4: StringSplit(abc(global_99_st_si11[tmp_in_3]), us1, local_22_st_si2);
        StringSplit(TrimString(symbols[i]), separator_char, parts);
        
        // 原MQL4: global_99_st_si11[tmp_in_3] = local_22_st_si2[0];
        symbols[i] = parts[0];
        
        // 原MQL4: global_100_do_si11[tmp_in_3] = (ArraySize(local_22_st_si2) == 2) ? StringToDouble(local_22_st_si2[1]) : global_35_do;
        coefficients[i] = (ArraySize(parts) == 2) ? StringToDouble(parts[1]) : g_lot_multiplier;
        
        // 原MQL4: Print(global_99_st_si11[tmp_in_3], " ", global_100_do_si11[tmp_in_3]);
        Print(symbols[i], " ", coefficients[i]);
    }
}

//+------------------------------------------------------------------+
//| 复制策略配置 (原xx3函数)
//+------------------------------------------------------------------+
void CopyStrategyConfigs(S_StrategyConfig &source[], S_StrategyConfig &target[])
{
    // 原MQL4: ArrayResize(global_2_a_160_, ArraySize(local_19_st), 0);
    ArrayResize(target, ArraySize(source), 0);
    
    // 原MQL4: for (int tmp_in_5 = 0; tmp_in_5 < ArraySize(local_19_st); tmp_in_5++)
    for (int i = 0; i < ArraySize(source); i++)
    {
        // 原MQL4: yy(global_2_a_160_[tmp_in_5], local_19_st[tmp_in_5]);
        SwapStrategyConfigs(target[i], source[i]);
    }
}

//+------------------------------------------------------------------+
//| 交换策略配置 (原yy函数)
//+------------------------------------------------------------------+
void SwapStrategyConfigs(S_StrategyConfig &config1, S_StrategyConfig &config2)
{
    // 原MQL4: xx.st_1 = yy.st_1; xx.in_2 = yy.in_2; 等等
    config1.strategy_name = config2.strategy_name;
    config1.parameter_1 = config2.parameter_1;
    config1.parameter_2 = config2.parameter_2;
    config1.parameter_3 = config2.parameter_3;
    config1.parameter_4 = config2.parameter_4;
    config1.parameter_5 = config2.parameter_5;
    config1.parameter_6 = config2.parameter_6;
    config1.parameter_7 = config2.parameter_7;
}

//+------------------------------------------------------------------+
//| 初始化虚拟订单
//+------------------------------------------------------------------+
void InitializeVirtualOrders()
{
    // 设置虚拟订单的全局变量
    string vtp_key_buy = IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + 
                        "0" + IntegerToString(g_virtual_magic);
    string vtp_key_sell = IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + 
                         "1" + IntegerToString(g_virtual_magic);
    string vtp_key_number = IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + 
                           g_current_symbol + IntegerToString(g_virtual_magic);
    string vtp_key_peak = IntegerToString(MQLInfoInteger(MQL_TESTER)) + g_current_symbol + 
                         IntegerToString(g_virtual_magic) + "peak";
    
    // 初始化虚拟订单状态
    GlobalVariableSet(vtp_key_buy, 0.0);
    GlobalVariableSet(vtp_key_sell, 0.0);
    GlobalVariableSet(vtp_key_number, 0.0);
    GlobalVariableSet(vtp_key_peak, 0.0);
    
    // 删除相关的图表对象
    ObjectDelete(0, IntegerToString(g_current_magic));
}

//+------------------------------------------------------------------+
//| 设置虚拟订单编号 (原SetNUMBER函数)
//+------------------------------------------------------------------+
void SetVirtualOrderNumber(string symbol, int type, int magic)
{
    long min_number = 0;
    int total_positions = PositionsTotal();
    
    // 检查全局符号
    if (g_current_symbol == "0")
        symbol = g_current_symbol;
    
    // 遍历所有持仓
    for (int i = 0; i < total_positions; i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        // 检查符号和注释
        if ((PositionGetString(POSITION_SYMBOL) != symbol && symbol != "") || 
            StringFind(PositionGetString(POSITION_COMMENT), "_C", 0) == -1)
            continue;
            
        // 检查持仓类型
        if (PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && 
            PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL)
            continue;
            
        // 检查指定的持仓类型
        if (type >= 0 && PositionGetInteger(POSITION_TYPE) != type)
            continue;
            
        // 检查魔术号
        if (magic > 0 || 
            PositionGetInteger(POSITION_MAGIC) == magic || 
            PositionGetInteger(POSITION_MAGIC) == g_current_magic)
        {
            // 从注释中提取编号
            string comment = PositionGetString(POSITION_COMMENT);
            int pos = StringFind(comment, "_C", 0);
            if (pos >= 0)
            {
                long number = StringToInteger(StringSubstr(comment, pos + 2));
                // 总是取最小值 (原MQ4: tmp_do_57 = (tmp_do_60 <= tmp_do_57) ? tmp_do_60 : tmp_do_57)
                min_number = (number <= min_number || min_number == 0) ? number : min_number;
            }
        }
    }
    
    // 设置全局变量
    string number_key = IntegerToString(MQLInfoInteger(MQL_TESTER)) + "NUMBER" + 
                       g_current_symbol + IntegerToString(g_virtual_magic);
    GlobalVariableSet(number_key, (double)g_grid_level);
Print("[GridLevel] Saved to GlobalVariable -", g_grid_level, "- Symbol:", g_current_symbol, ", Magic:", g_current_magic);  // 使用当前网格级别，而不是min_number
    

}

//+------------------------------------------------------------------+
//| 清理测试环境 (原rrr函数)
//+------------------------------------------------------------------+
void CleanupTestEnvironment()
{
    // 原MQL4: if (MQLInfoInteger(MQL_TESTER))
    if (MQLInfoInteger(MQL_TESTER))
    {
        // 在测试模式下，先开一个测试订单，然后立即平仓
        // 原MQL4: lizong_15(Symbol(), 0, SymbolInfoDouble(NULL, 34), 0, 0, 123123123, "", 0.0);
        g_current_magic = 123123123; // 临时设置测试魔术号
        g_current_symbol = Symbol(); // 确保使用当前图表符号
        ExecuteBuyOrder(SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MIN), "");
        
        // 原MQL4: lizong_17(Symbol(), -1, 123123123);
        ClosePositions(Symbol(), -1, 123123123);
        
        Print("清理测试环境完成 - 测试模式");
    }
}

//+------------------------------------------------------------------+
//| 特殊逻辑处理 (原lizong80函数)
//+------------------------------------------------------------------+
void ProcessSpecialLogic(int order_ticket)
{
    // 原MQL4: if (MQLInfoInteger(MQL_TESTER) && global_48_bo)
    if (MQLInfoInteger(MQL_TESTER) && g_enable_visual_mode)
    {
        // 原MQL4: global_86_st_si40000[global_88_in] = "C" + string(global_14_in) + "," + string(global_18_in) + "," + string(global_58_do / MarketInfo(global_50_st, 9));
        string order_info = "C" + IntegerToString(g_grid_level) + "," + 
                          IntegerToString(g_ma_period) + "," + 
                          DoubleToString(g_stddev_value / SymbolInfoDouble(g_current_symbol, SYMBOL_BID), 2);
                          
        // 原MQL4: global_87_in_si40000[global_88_in] = local_8_in;
        g_int_array[g_array_index_1] = order_ticket;
        
        // 原MQL4: global_88_in++;
        g_array_index_1++;
    }
}

//+------------------------------------------------------------------+
//| 检查持仓数量 (原lizongs6int函数)
//+------------------------------------------------------------------+
int CheckPositionCount(int magic, string symbol)
{
    int total_positions = PositionsTotal();
    int magic_numbers[];  // 存储不同的魔术号
    ArrayResize(magic_numbers, 0);
    
    // 遍历所有持仓
    for (int i = 0; i < total_positions; i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        // 检查符号
        if (symbol != "" && PositionGetString(POSITION_SYMBOL) != symbol)
            continue;
            
        // 检查持仓类型和魔术号
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && 
             PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL) || 
             PositionGetInteger(POSITION_MAGIC) == magic)
            continue;
            
        // 检查魔术号是否已经记录
        bool found = false;
        for (int j = 0; j < ArraySize(magic_numbers); j++)
        {
            if (magic_numbers[j] == PositionGetInteger(POSITION_MAGIC))
            {
                found = true;
                break;
            }
        }
        
        // 如果是新的魔术号，添加到数组
        if (!found)
        {
            int size = ArraySize(magic_numbers);
            ArrayResize(magic_numbers, size + 1);
            magic_numbers[size] = (int)PositionGetInteger(POSITION_MAGIC);
        }
    }
    
    return ArraySize(magic_numbers);
}

//+------------------------------------------------------------------+
//| 检查字符串值 (原lizongs6str函数)
//+------------------------------------------------------------------+
int CheckStringValue(string symbol)
{
    int total_positions = PositionsTotal();
    string symbols[];  // 存储不同的交易品种
    ArrayResize(symbols, 0);
    
    // 检查全局符号
    if (g_current_symbol == "0")
        symbol = g_current_symbol;
    
    // 遍历所有持仓
    for (int i = 0; i < total_positions; i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)) || 
            PositionGetString(POSITION_SYMBOL) == symbol)
            continue;
            
        // 检查持仓类型
        if (PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && 
            PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL)
            continue;
            
        // 检查符号是否已经记录
        bool found = false;
        for (int j = 0; j < ArraySize(symbols); j++)
        {
            if (symbols[j] == PositionGetString(POSITION_SYMBOL))
            {
                found = true;
                break;
            }
        }
        
        // 如果是新的符号，添加到数组
        if (!found)
        {
            int size = ArraySize(symbols);
            ArrayResize(symbols, size + 1);
            symbols[size] = PositionGetString(POSITION_SYMBOL);
        }
    }
    
    return ArraySize(symbols);
}

//+------------------------------------------------------------------+
//| 策略配置结构体方法实现
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| 初始化策略8 (原_sets_8函数)
//+------------------------------------------------------------------+
void S_StrategyConfig::InitializeStrategy8()
{
    // 设置策略名称和参数
    strategy_name = "Set8";
    parameter_1 = 8;
    parameter_2 = 1.4;    // 马丁系数
    parameter_3 = 0.4;    // 止盈系数
    parameter_4 = 1.0;    // 网格系数
    parameter_5 = 50.0;   // 网格间距
    parameter_6 = 1.5;    // 解锁系数
    parameter_7 = 0.0;    // 保留参数
}

//+------------------------------------------------------------------+
//| 初始化策略9 (原_sets_9函数)
//+------------------------------------------------------------------+
void S_StrategyConfig::InitializeStrategy9()
{
    // 设置策略名称和参数
    strategy_name = "Set9";
    parameter_1 = 9;
    parameter_2 = 1.4;    // 马丁系数
    parameter_3 = 0.4;    // 止盈系数
    parameter_4 = 1.0;    // 网格系数
    parameter_5 = 50.0;   // 网格间距
    parameter_6 = 1.5;    // 解锁系数
    parameter_7 = 0.0;    // 保留参数
}

//+------------------------------------------------------------------+
//| 初始化策略10 (原_sets_10函数)
//+------------------------------------------------------------------+
void S_StrategyConfig::InitializeStrategy10()
{
    // 设置策略名称和参数
    strategy_name = "Set10";
    parameter_1 = 10;
    parameter_2 = 1.4;    // 马丁系数
    parameter_3 = 0.4;    // 止盈系数
    parameter_4 = 1.0;    // 网格系数
    parameter_5 = 50.0;   // 网格间距
    parameter_6 = 1.5;    // 解锁系数
    parameter_7 = 0.0;    // 保留参数
}

//+------------------------------------------------------------------+
//| 初始化策略11 (原_sets_11函数)
//+------------------------------------------------------------------+
void S_StrategyConfig::InitializeStrategy11()
{
    // 设置策略名称和参数
    strategy_name = "Set11";
    parameter_1 = 11;
    parameter_2 = 1.4;    // 马丁系数
    parameter_3 = 0.4;    // 止盈系数
    parameter_4 = 1.0;    // 网格系数
    parameter_5 = 50.0;   // 网格间距
    parameter_6 = 1.5;    // 解锁系数
    parameter_7 = 0.0;    // 保留参数
}

//+------------------------------------------------------------------+
//| 新增的辅助函数实现
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| 初始化策略配置 (原OnInit中的策略配置部分 - 对应lizong_23函数逻辑)
//+------------------------------------------------------------------+
void InitializeStrategyConfigs()
{
    // 创建预设策略配置
    S_StrategyConfig set1_159 = {"Set1-159", 159, 1.4, 0.4, 1, 50, 1.5, 0};
    S_StrategyConfig set1_318 = {"Set1-318", 318, 1.4, 0.4, 1, 50, 1.5, 0};
    S_StrategyConfig set1_635 = {"Set1-635", 635, 1.4, 0.4, 1, 50, 1.5, 0};
    S_StrategyConfig set1_225 = {"Set1-225", 225, 1.4, 0.4, 1, 50, 1.5, 0};
    S_StrategyConfig set1_450 = {"Set1-450", 450, 1.4, 0.4, 1, 50, 1.5, 0};
    S_StrategyConfig set2_200 = {"Set2-200", 200, 1.35, 0.7, 0.9, 70, 1.5, 0};
    S_StrategyConfig set2_400 = {"Set2-400", 400, 1.4, 0.7, 0.9, 70, 1.5, 0};
    S_StrategyConfig set2_800 = {"Set2-800", 800, 1.4, 0.65, 0.85, 30, 1.5, 0};
    S_StrategyConfig set2_283 = {"Set2-283", 283, 1.4, 0.7, 0.9, 70, 1.5, 0};
    S_StrategyConfig set2_566 = {"Set2-566", 566, 1.4, 0.7, 0.9, 70, 1.5, 0};
    S_StrategyConfig set3_252 = {"Set3-252", 252, 1.4, 0.9, 0.8, 60, 1.5, 0};
    S_StrategyConfig set3_504 = {"Set3-504", 504, 1.4, 0.9, 0.8, 60, 1.5, 0};
    S_StrategyConfig set3_1008 = {"Set3-1008", 1008, 1.4, 0.85, 0.75, 20, 1.5, 0};
    S_StrategyConfig set3_356 = {"Set3-356", 356, 1.4, 0.9, 0.8, 60, 1.5, 0};
    S_StrategyConfig set3_713 = {"Set3-713", 713, 1.4, 0.85, 0.75, 20, 1.5, 0};
    
    // 根据策略类型设置配置
    if (g_strategy_type == STRATEGY_CUSTOM && TrimString(CustomStrategyConfig) == "")
    {
        g_max_strategies = 1;
    }
    else if (g_strategy_type == STRATEGY_CUSTOM && TrimString(CustomStrategyConfig) != "")
    {
        // 加载自定义策略配置 (原lizong_23函数逻辑)
        LoadCustomStrategyConfigs(CustomStrategyConfig);
    }
    else if (g_strategy_type == STRATEGY_1_3ADVISORS)
    {
        ArrayResize(g_strategy_configs, 3, 0);
        g_max_strategies = 3;
        SwapStrategyConfigs(g_strategy_configs[0], set1_159);
        SwapStrategyConfigs(g_strategy_configs[1], set1_318);
        SwapStrategyConfigs(g_strategy_configs[2], set1_635);
    }
    else if (g_strategy_type == 3)
    {
        ArrayResize(g_strategy_configs, 3, 0);
        g_max_strategies = 3;
        SwapStrategyConfigs(g_strategy_configs[0], set2_200);
        SwapStrategyConfigs(g_strategy_configs[1], set2_400);
        SwapStrategyConfigs(g_strategy_configs[2], set2_800);
    }
    else if (g_strategy_type == 4)
    {
        ArrayResize(g_strategy_configs, 3, 0);
        g_max_strategies = 3;
        SwapStrategyConfigs(g_strategy_configs[0], set3_252);
        SwapStrategyConfigs(g_strategy_configs[1], set3_504);
        SwapStrategyConfigs(g_strategy_configs[2], set3_1008);
    }
    else if (g_strategy_type == 5)
    {
        ArrayResize(g_strategy_configs, 9, 0);
        g_max_strategies = 9;
        SwapStrategyConfigs(g_strategy_configs[0], set1_159);
        SwapStrategyConfigs(g_strategy_configs[1], set1_318);
        SwapStrategyConfigs(g_strategy_configs[2], set1_635);
        SwapStrategyConfigs(g_strategy_configs[3], set2_200);
        SwapStrategyConfigs(g_strategy_configs[4], set2_400);
        SwapStrategyConfigs(g_strategy_configs[5], set2_800);
        SwapStrategyConfigs(g_strategy_configs[6], set3_252);
        SwapStrategyConfigs(g_strategy_configs[7], set3_504);
        SwapStrategyConfigs(g_strategy_configs[8], set3_1008);
    }
    else if (g_strategy_type == 6)
    {
        ArrayResize(g_strategy_configs, 3, 0);
        g_max_strategies = 3;
        SwapStrategyConfigs(g_strategy_configs[0], set1_318);
        SwapStrategyConfigs(g_strategy_configs[1], set2_400);
        SwapStrategyConfigs(g_strategy_configs[2], set3_504);
    }
    else if (g_strategy_type == 7)
    {
        ArrayResize(g_strategy_configs, 15, 0);
        g_max_strategies = 15;
        SwapStrategyConfigs(g_strategy_configs[0], set1_159);
        SwapStrategyConfigs(g_strategy_configs[1], set1_318);
        SwapStrategyConfigs(g_strategy_configs[2], set1_635);
        SwapStrategyConfigs(g_strategy_configs[3], set1_225);
        SwapStrategyConfigs(g_strategy_configs[4], set1_450);
        SwapStrategyConfigs(g_strategy_configs[5], set2_200);
        SwapStrategyConfigs(g_strategy_configs[6], set2_400);
        SwapStrategyConfigs(g_strategy_configs[7], set2_800);
        SwapStrategyConfigs(g_strategy_configs[8], set2_283);
        SwapStrategyConfigs(g_strategy_configs[9], set2_566);
        SwapStrategyConfigs(g_strategy_configs[10], set3_252);
        SwapStrategyConfigs(g_strategy_configs[11], set3_504);
        SwapStrategyConfigs(g_strategy_configs[12], set3_1008);
        SwapStrategyConfigs(g_strategy_configs[13], set3_356);
        SwapStrategyConfigs(g_strategy_configs[14], set3_713);
    }
}

//+------------------------------------------------------------------+
//| 计算魔术号 (原zs1函数)
//+------------------------------------------------------------------+
string CalculateMagicNumber(string symbol)
{
    if (StringLen(symbol) != 6)
    {
        return "99";
    }
    
    string part1 = StringSubstr(symbol, 0, 3);
    string part2 = StringSubstr(symbol, 3, 3);
    
    // 原MQL4: return (lizong_20(w1) + lizong_20(w2));
    // 这里简化处理，直接返回字符串
    return part1 + part2;
}

//+------------------------------------------------------------------+
//| 计算完整魔术号 (原zs2函数)
//+------------------------------------------------------------------+
string CalculateFullMagicNumber(string strategy_string)
{
    string symbol_magic = CalculateMagicNumber(g_current_symbol);
    return symbol_magic + IntegerToString(ServerNumber, 2, '0') + strategy_string;
}

//+------------------------------------------------------------------+
//| 字符串修剪 (原abc函数)
//+------------------------------------------------------------------+
string TrimString(string str)
{
    // 原MQL4: return (StringTrimLeft(StringTrimRight(s1)));
    // MQL5中使用StringTrimLeft和StringTrimRight函数
    StringTrimLeft(str);
    StringTrimRight(str);
    return str;
}

//+------------------------------------------------------------------+
//| 加载自定义策略配置 (原lizong_23函数)
//+------------------------------------------------------------------+
void LoadCustomStrategyConfigs(string config_string)
{
    string main_parts[];
    string strategy_parts[];
    string param_parts[];
    
    // 原MQL4: StringSplit(para_0_st, StringGetCharacter(";", 0), local_1_st_ko);
    StringSplit(config_string, StringGetCharacter(";", 0), main_parts);
    
    int main_count = ArraySize(main_parts);
    for (int i = 0; i < main_count; i++)
    {
        // 原MQL4: local_1_st_ko[tmp_in_2] = StringTrimLeft(StringTrimRight(local_1_st_ko[tmp_in_2]));
        StringTrimLeft(main_parts[i]);
        StringTrimRight(main_parts[i]);
    }
    
    int strategy_count = 0;
    int max_strategies = MathMin(7318875, 9); // 原MQL4: tmp_in_10 = 7318875
    
    while (strategy_count < max_strategies)
    {
        if (TrimString(main_parts[strategy_count]) != "")
        {
            // 原MQL4: ArrayResize(para_1_a_160__sets_ko, tmp_in_3 + 1, 0);
            ArrayResize(g_strategy_configs, strategy_count + 1, 0);
            
            // 设置默认值 (原MQL4中的local_11_st等)
            // 原MQL4: para_1_a_160__sets_ko[tmp_in_3].st_1 = local_11_st; 等等
            // 原MQL4: local_10_in = global_19_in; local_9_do = global_21_do; 等等
            g_strategy_configs[strategy_count].strategy_name = "base";
            g_strategy_configs[strategy_count].parameter_1 = g_ma_period;        // 原global_19_in
            g_strategy_configs[strategy_count].parameter_2 = g_stddev_multiplier; // 原global_21_do
            g_strategy_configs[strategy_count].parameter_3 = g_virtual_tp_coeff1; // 原global_28_do
            g_strategy_configs[strategy_count].parameter_4 = g_virtual_tp_coeff2; // 原global_29_do
            g_strategy_configs[strategy_count].parameter_5 = g_unlock_percent;    // 原global_30_in
            g_strategy_configs[strategy_count].parameter_6 = g_tp_price_coefficient; // 原global_31_do
            g_strategy_configs[strategy_count].parameter_7 = g_virtual_tp_coeff3;  // 原global_33_do
            
            int set_number = strategy_count + 1;
            PrintFormat("使用策略 #%d: %s", set_number, main_parts[strategy_count]);
            
            // 解析策略参数 (原MQL4: StringSplit(local_1_st_ko[tmp_in_3], StringGetCharacter(",", 0), local_2_st_ko))
            StringSplit(main_parts[strategy_count], StringGetCharacter(",", 0), strategy_parts);
            int param_count = ArraySize(strategy_parts);
            
            for (int j = 0; j < param_count; j++)
            {
                StringTrimLeft(strategy_parts[j]);
                StringTrimRight(strategy_parts[j]);
            }
            
            for (int j = 0; j < ArrayRange(strategy_parts, 0); j++)
            {
                // 原MQL4: StringSplit(local_2_st_ko[tmp_in_3], StringGetCharacter("=", 0), local_3_st_ko);
                StringSplit(strategy_parts[j], StringGetCharacter("=", 0), param_parts);
                int param_parts_count = ArraySize(param_parts);
                
                for (int k = 0; k < param_parts_count; k++)
                {
                    StringTrimLeft(param_parts[k]);
                    StringTrimRight(param_parts[k]);
                }
                
                // 根据参数名设置对应的值 (原MQL4中的if-else逻辑)
                if (param_parts[0] == "s1")
                {
                    g_strategy_configs[strategy_count].strategy_name = param_parts[1];
                }
                else if (param_parts[0] == "s2")
                {
                    g_strategy_configs[strategy_count].parameter_1 = StringToInteger(param_parts[1]);
                }
                else if (param_parts[0] == "s3")
                {
                    g_strategy_configs[strategy_count].parameter_2 = StringToDouble(param_parts[1]);
                }
                else if (param_parts[0] == "s4")
                {
                    g_strategy_configs[strategy_count].parameter_3 = StringToDouble(param_parts[1]);
                }
                else if (param_parts[0] == "s5")
                {
                    g_strategy_configs[strategy_count].parameter_4 = StringToDouble(param_parts[1]);
                }
                else if (param_parts[0] == "s6")
                {
                    g_strategy_configs[strategy_count].parameter_5 = StringToDouble(param_parts[1]);
                }
                else if (param_parts[0] == "s7")
                {
                    g_strategy_configs[strategy_count].parameter_6 = StringToDouble(param_parts[1]);
                }
                else if (param_parts[0] == "s8")
                {
                    g_strategy_configs[strategy_count].parameter_7 = StringToDouble(param_parts[1]);
                }
            }
        }
        strategy_count++;
    }
    
    g_max_strategies = ArraySize(g_strategy_configs);
}

//+------------------------------------------------------------------+
//| 创建矩形标签 (原lizong_25函数)
//+------------------------------------------------------------------+
bool CreateRectangleLabel(long chart_id, string name, int sub_window, int x, int y, int width, int height, int bg_color, int border_type, int corner, int border_color, int style, int width_px, bool back, bool selectable, bool selected, bool hidden, long z_order)
{
    ResetLastError();
    if(ObjectFind(chart_id, name) >= 0)
    {
        ObjectDelete(chart_id, name);
    }
    if(!ObjectCreate(chart_id, name, OBJ_RECTANGLE_LABEL, sub_window, 0, 0.0))
    {
        Print("RectLabelCreate: 无法创建矩形标签! 错误代码 = ", GetLastError());
        return false;
    }
    ObjectSetInteger(chart_id, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(chart_id, name, OBJPROP_YDISTANCE, y);
    ObjectSetInteger(chart_id, name, OBJPROP_XSIZE, width);
    ObjectSetInteger(chart_id, name, OBJPROP_YSIZE, height);
    ObjectSetInteger(chart_id, name, OBJPROP_BGCOLOR, bg_color);
    ObjectSetInteger(chart_id, name, OBJPROP_BORDER_TYPE, border_type);
    ObjectSetInteger(chart_id, name, OBJPROP_CORNER, corner);
    ObjectSetInteger(chart_id, name, OBJPROP_COLOR, border_color);
    ObjectSetInteger(chart_id, name, OBJPROP_STYLE, style);
    ObjectSetInteger(chart_id, name, OBJPROP_WIDTH, width_px);
    ObjectSetInteger(chart_id, name, OBJPROP_BACK, back);
    ObjectSetInteger(chart_id, name, OBJPROP_SELECTABLE, selectable);
    ObjectSetInteger(chart_id, name, OBJPROP_SELECTED, selected);
    ObjectSetInteger(chart_id, name, OBJPROP_HIDDEN, hidden);
    ObjectSetInteger(chart_id, name, OBJPROP_ZORDER, z_order);
    return true;
}

//+------------------------------------------------------------------+
//| 初始化界面显示 (原lizong_26函数)
//+------------------------------------------------------------------+
void InitializeInterfaceDisplay()
{
    int x_pos = 10;
    int y_pos = 20;
    int width = g_counter_4 * 210 / 100;  // 原local_3_in = global_102_in * 210 / 100
    int height = 310;
    
    // 创建主背景矩形
    if(!CreateRectangleLabel(0, "RectLabel", 0, x_pos, y_pos, width, height, 8421504, 1, 0, 9109504, 0, 2, false, false, false, false, 1))
        return;
    
    y_pos = 20 + 5;
    x_pos = g_counter_4 * 5 / 100 + 10;  // 原local_1_in = global_102_in * 5 / 100 + 10
    int label_width = g_counter_4 * 120 / 100;  // 原local_5_in = global_102_in * 120 / 100
    int line_height = 15;  // 原local_6_in = 15
    
    // 账户杠杆信息
    string leverage_text = StringFormat("1:%I64d", AccountInfoInteger(ACCOUNT_LEVERAGE));  // 原local_7_st = StringFormat("1:%I64d", AccountLeverage())
    string currency_text = "";
    
    if(g_virtual_tp_coeff3 > 0.0)  // 原global_34_do > 0.0
    {
        if(ArraySize(g_symbol_list) == 1)  // 原ArraySize(global_99_st_si1) == 1
        {
            string usd_text = DoubleToString(USDFor001, 0);  // 原tmp_st_1 = DoubleToString(USD_for_001, 0)
            if(g_symbol_coefficients[0] == 1.0)  // 原global_100_do_si1[0] == 1.0
            {
                currency_text = usd_text;
            }
            else
            {
                currency_text = usd_text + "(*" + DoubleToString(g_symbol_coefficients[0], 0) + ")";
            }
        }
        else
        {
            currency_text = DoubleToString(USDFor001, 0);
        }
    }
    else
    {
        currency_text = "fix lot=" + DoubleToString(Lots, 2);  // 原string(Lots)
    }
    
    // 创建标题
    int title_color = 16777215;  // 原tmp_in_3 = 16777215
    int title_font_size = 11;    // 原tmp_in_4 = 11
    string title_text = "NorthEastWay MT5 v" + g_version;  // 原tmp_st_7 = "NorthEastWay MT4 v" + global_1_st
    
    if(ObjectFind(0, "s1") >= 0)
        ObjectDelete(0, "s1");
    
    if(ObjectCreate(0, "s1", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "s1", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "s1", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "s1", OBJPROP_XDISTANCE, x_pos);
        ObjectSetInteger(0, "s1", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "s1", OBJPROP_FONTSIZE, title_font_size);
        ObjectSetInteger(0, "s1", OBJPROP_COLOR, title_color);
        ObjectSetInteger(0, "s1", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "s1", OBJPROP_TEXT, title_text);
        ObjectSetString(0, "s1", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "s1", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "s1", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "s1", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "s1", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        // 添加到界面对象数组
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "s1";
    }
    
    y_pos += line_height;
    
    // 创建分隔线
    int separator_color = 16777215;  // 原tmp_in_9 = 16777215
    int separator_font_size = 9;     // 原tmp_in_10 = 9
    string separator_text = "-------------------------------";  // 原tmp_st_13 = "-------------------------------"
    
    if(ObjectFind(0, "s2") >= 0)
        ObjectDelete(0, "s2");
    
    if(ObjectCreate(0, "s2", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "s2", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "s2", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "s2", OBJPROP_XDISTANCE, x_pos);
        ObjectSetInteger(0, "s2", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "s2", OBJPROP_FONTSIZE, separator_font_size);
        ObjectSetInteger(0, "s2", OBJPROP_COLOR, separator_color);
        ObjectSetInteger(0, "s2", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "s2", OBJPROP_TEXT, separator_text);
        ObjectSetString(0, "s2", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "s2", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "s2", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "s2", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "s2", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "s2";
    }
    
    y_pos += line_height;
    
    // 创建账户杠杆标签
    int label_color = 16777215;  // 原tmp_in_15 = 16777215
    int label_font_size = 9;     // 原tmp_in_16 = 9
    string leverage_label = "Acc leverage:";  // 原tmp_st_19 = "Acc leverage:"
    
    if(ObjectFind(0, "se1") >= 0)
        ObjectDelete(0, "se1");
    
    if(ObjectCreate(0, "se1", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "se1", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "se1", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "se1", OBJPROP_XDISTANCE, x_pos);
        ObjectSetInteger(0, "se1", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "se1", OBJPROP_FONTSIZE, label_font_size);
        ObjectSetInteger(0, "se1", OBJPROP_COLOR, label_color);
        ObjectSetInteger(0, "se1", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "se1", OBJPROP_TEXT, leverage_label);
        ObjectSetString(0, "se1", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "se1", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "se1", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "se1", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "se1", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "se1";
    }
    
    // 创建账户杠杆值
    int value_color = 16777215;  // 原tmp_in_21 = 16777215
    int value_font_size = 9;     // 原tmp_in_22 = 9
    string leverage_value = leverage_text;  // 原tmp_st_25 = local_7_st
    
    if(ObjectFind(0, "AccLever") >= 0)
        ObjectDelete(0, "AccLever");
    
    if(ObjectCreate(0, "AccLever", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "AccLever", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "AccLever", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "AccLever", OBJPROP_XDISTANCE, x_pos + label_width);
        ObjectSetInteger(0, "AccLever", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "AccLever", OBJPROP_FONTSIZE, value_font_size);
        ObjectSetInteger(0, "AccLever", OBJPROP_COLOR, value_color);
        ObjectSetInteger(0, "AccLever", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "AccLever", OBJPROP_TEXT, leverage_value);
        ObjectSetString(0, "AccLever", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "AccLever", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "AccLever", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "AccLever", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "AccLever", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "AccLever";
    }
    
    y_pos += line_height;
    
    // 创建货币标签
    int currency_label_color = 16777215;  // 原tmp_in_27 = 16777215
    int currency_label_font_size = 9;     // 原tmp_in_28 = 9
    string currency_label_text = "Currency:";  // 原tmp_st_31 = "Currency:"
    
    if(ObjectFind(0, "curr_lab") >= 0)
        ObjectDelete(0, "curr_lab");
    
    if(ObjectCreate(0, "curr_lab", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "curr_lab", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "curr_lab", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "curr_lab", OBJPROP_XDISTANCE, x_pos);
        ObjectSetInteger(0, "curr_lab", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "curr_lab", OBJPROP_FONTSIZE, currency_label_font_size);
        ObjectSetInteger(0, "curr_lab", OBJPROP_COLOR, currency_label_color);
        ObjectSetInteger(0, "curr_lab", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "curr_lab", OBJPROP_TEXT, currency_label_text);
        ObjectSetString(0, "curr_lab", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "curr_lab", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "curr_lab", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "curr_lab", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "curr_lab", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "curr_lab";
    }
    
    // 创建货币值
    int currency_value_color = 16777215;  // 原tmp_in_33 = 16777215
    int currency_value_font_size = 9;     // 原tmp_in_34 = 9
    string currency_value_text;
    
    if(ArraySize(g_symbol_list) > 1)  // 原ArraySize(global_99_st_si1) > 1
    {
        currency_value_text = "Multi Mode";  // 原tmp_st_37 = "Multi Mode"
    }
    else
    {
        currency_value_text = currency_text;  // 原local_8_st
    }
    
    if(ObjectFind(0, "curr_val") >= 0)
        ObjectDelete(0, "curr_val");
    
    if(ObjectCreate(0, "curr_val", OBJ_LABEL, 0, 0, 0.0))
    {
        ObjectSetInteger(0, "curr_val", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
        ObjectSetInteger(0, "curr_val", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "curr_val", OBJPROP_XDISTANCE, x_pos + label_width);
        ObjectSetInteger(0, "curr_val", OBJPROP_YDISTANCE, y_pos);
        ObjectSetInteger(0, "curr_val", OBJPROP_FONTSIZE, currency_value_font_size);
        ObjectSetInteger(0, "curr_val", OBJPROP_COLOR, currency_value_color);
        ObjectSetInteger(0, "curr_val", OBJPROP_SELECTABLE, 1);
        ObjectSetString(0, "curr_val", OBJPROP_TEXT, currency_value_text);
        ObjectSetString(0, "curr_val", OBJPROP_FONT, "Calibri");
        ObjectSetInteger(0, "curr_val", OBJPROP_SELECTED, 0);
        ObjectSetInteger(0, "curr_val", OBJPROP_HIDDEN, 0);
        ObjectSetInteger(0, "curr_val", OBJPROP_ZORDER, 1);
        ObjectSetInteger(0, "curr_val", OBJPROP_SELECTABLE, 0);
        ChartRedraw(0);
        
        int array_size = ArraySize(g_symbol_array);
        ArrayResize(g_symbol_array, array_size + 1, 0);
        g_symbol_array[array_size] = "curr_val";
    }
    
    Print("界面显示初始化完成 - 原lizong_26函数");
} 


//+------------------------------------------------------------------+
//| 计算延迟时间 (原DELAYtime函数)
//+------------------------------------------------------------------+
datetime DELAYtime(string symbol, int type, int magic, string comment, datetime current_time)
{
    string check_symbol = symbol;
    datetime last_order_time = 0;
    
    if (g_current_symbol == "0")
        check_symbol = g_current_symbol;
    
    // 遍历所有持仓
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        // 检查符号
        if (PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != "")
            continue;
            
        // 检查注释
        if (StringFind(PositionGetString(POSITION_COMMENT), comment, 0) != -1 && comment != "")
            continue;
            
        // 检查持仓类型
        if (PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && 
            PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL)
            continue;
            
        // 检查指定类型
        if (type >= 0 && PositionGetInteger(POSITION_TYPE) != type)
            continue;
            
        // 检查魔术号
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic && 
             PositionGetInteger(POSITION_MAGIC) != g_current_magic) || 
            !(last_order_time < (datetime)PositionGetInteger(POSITION_TIME)))
            continue;
            
        last_order_time = (datetime)PositionGetInteger(POSITION_TIME);
    }
    
    return current_time - last_order_time;
} 

//+------------------------------------------------------------------+
//| 获取符号名称 (原lizongs1函数)
//+------------------------------------------------------------------+
string GetSymbolName(string symbol)
{
    if (StringLen(symbol) <= 5)
    {
        Print("Symbol name " + symbol + " from sets is too short. Perhaps you made a mistake in writing.");
        return "";
    }
    
    for (int i = 0; i < SymbolsTotal(true); i++)
    {
        string symbol_name = SymbolName(i, true);
        string original_name = symbol_name;
        StringToUpper(symbol_name);
        StringToUpper(symbol);
        if (StringFind(symbol_name, symbol, 0) >= 0)
        {
            return original_name;
        }
    }
    
    Print("Symbol " + symbol + " from sets not found in MarketWatch. Add this symbol to MarketWatch.");
    return "";
}


//+------------------------------------------------------------------+
//| 获取其他魔术号数量 (原lizongs6int)
//+------------------------------------------------------------------+
int GetOtherMagicsCount(int magic, string symbol)
{
    int total_positions = PositionsTotal();
    int other_magics[];  // 存储其他魔术号的数组
    ArrayResize(other_magics, 0);
    
    for (int i = 0; i < total_positions; i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        // 如果指定了符号且不匹配，跳过
        if (symbol != "" && PositionGetString(POSITION_SYMBOL) != symbol)
            continue;
            
        // 只处理买单和卖单，且排除当前魔术号
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL) || 
            PositionGetInteger(POSITION_MAGIC) == magic)
            continue;
            
        // 检查魔术号是否已经记录
        bool found = false;
        for (int j = 0; j < ArraySize(other_magics); j++)
        {
            if (other_magics[j] == PositionGetInteger(POSITION_MAGIC))
            {
                found = true;
                break;
            }
        }
        
        // 如果没找到，添加到数组
        if (!found)
        {
            int size = ArraySize(other_magics);
            ArrayResize(other_magics, size + 1);
            other_magics[size] = (int)PositionGetInteger(POSITION_MAGIC);
        }
    }
    
    return ArraySize(other_magics);
}

//+------------------------------------------------------------------+
//| 获取其他符号数量 (原lizongs6str)
//+------------------------------------------------------------------+
int GetOtherSymbolsCount(string symbol)
{
    int total_orders = PositionsTotal();
    string other_symbols[];  // 存储其他符号的数组
    ArrayResize(other_symbols, 0);
    
    // 如果全局符号为"0"，使用全局符号作为参数
    if (g_current_symbol == "0")
        symbol = g_current_symbol;
    
    for (int i = 0; i < total_orders; i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        // 跳过当前符号的持仓
        if (PositionGetString(POSITION_SYMBOL) == symbol)
            continue;
            
        // 只处理买单和卖单
        if (PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL)
            continue;
            
        // 检查符号是否已经记录
        bool found = false;
        for (int j = 0; j < ArraySize(other_symbols); j++)
        {
            if (other_symbols[j] == PositionGetString(POSITION_SYMBOL))
            {
                found = true;
                break;
            }
        }
        
        // 如果没找到，添加到数组
        if (!found)
        {
            int size = ArraySize(other_symbols);
            ArrayResize(other_symbols, size + 1);
            other_symbols[size] = PositionGetString(POSITION_SYMBOL);
        }
    }
    
    return ArraySize(other_symbols);
}

//+------------------------------------------------------------------+
//| 更新界面 (原lizongs7)
//+------------------------------------------------------------------+
void UpdateInterface()
{
    string object_name = "C" + IntegerToString(g_min_real_level + 1);
    int object_type = 1;  // 垂直线
    int object_time = 0;
    double object_price = g_grid_distance;
    string object_text = IntegerToString(g_current_magic);
    int object_color = (g_min_real_level + 1 >= FirstNumber) ? 255 : 8388736;  // 红色或蓝色
    
    // 如果魔术号为空，使用当前时间
    if (object_text == "")
        object_text = IntegerToString(TimeCurrent());
    
    // 如果距离价格为0，使用当前Bid价格
    if (object_price <= 0.0)
        object_price = SymbolInfoDouble(g_current_symbol, SYMBOL_BID);
    
    // 创建或更新图表对象
    if (ObjectFind(0, object_name) < 0)
        ObjectCreate(0, object_name, OBJ_VLINE, 0, 0, 0);
    
    ObjectSetString(0, object_name, OBJPROP_TEXT, object_text);
    ObjectSetDouble(0, object_name, OBJPROP_PRICE, object_price);
    ObjectSetInteger(0, object_name, OBJPROP_COLOR, object_color);
    ObjectSetInteger(0, object_name, OBJPROP_STYLE, object_time);
    ObjectSetInteger(0, object_name, OBJPROP_WIDTH, object_type);
}

//+------------------------------------------------------------------+
//| 获取持仓开仓价格 (原lizongs8)
//+------------------------------------------------------------------+
double GetPositionOpenPrice(int type, int magic)
{
    string symbol = g_current_symbol;
    double total_price = 0.0;
    double total_lots = 0.0;
    
    if (symbol == "")
        symbol = g_current_symbol;
    
    // 遍历所有持仓
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if (PositionGetString(POSITION_SYMBOL) != symbol || 
            PositionGetInteger(POSITION_MAGIC) != magic)
            continue;
            
        // 检查订单类型
        if ((type != -1 && PositionGetInteger(POSITION_TYPE) != type) || 
            PositionGetInteger(POSITION_TYPE) > POSITION_TYPE_SELL)
            continue;
            
        total_price += PositionGetDouble(POSITION_PRICE_OPEN) * PositionGetDouble(POSITION_VOLUME);
        total_lots += PositionGetDouble(POSITION_VOLUME);
    }
    
    if (total_lots == 0.0)
        return 0.0;
    else
        return NormalizeDouble(total_price / total_lots, _Digits);
}

//+------------------------------------------------------------------+
//| 检查虚拟止盈 (原lizongs9)
//+------------------------------------------------------------------+
// 构造全局变量键名 (保持与MQ4完全一致)
string GetGlobalVarKey(string prefix = "", string suffix = "")
{
    // MQ4 key format: string(IsTesting()) + prefix + symbol + suffix + string(virtual_magic)
    string key = IntegerToString((int)MQLInfoInteger(MQL_TESTER));
    key += prefix;
    key += g_current_symbol;
    key += suffix;
    key += IntegerToString(g_virtual_magic);
    
    return key;
}

// 设置全局变量 (保持与MQ4完全一致)
void SetGlobalVar(string prefix = "", string suffix = "", double value = 0.0)
{
    string key = GetGlobalVarKey(prefix, suffix);
    GlobalVariableSet(key, value);
}

// 检查虚拟止盈 (原MQ4: lizongs9)
bool CheckVirtualTakeProfit(int type)
{
    // 保持与MQ4完全一致的变量名构造顺序
    string vtp_key = GetGlobalVarKey("", IntegerToString(type));
    
    // 检查全局变量是否存在
    if (!GlobalVariableCheck(vtp_key))
        return false;

        // 检查值是否为1.0
        double value = GlobalVariableGet(vtp_key);
  
    
    if (value == 1.0){
        // Print("CheckVirtualTakeProfit - Key==================================:", vtp_key, ", GlobalVariableCheck===========================:", value, ", res:", value == 1.0);
        return true;
    }
       

    
    return false;
}

//+------------------------------------------------------------------+
//| 检查交易条件 (原lizongs10)
//+------------------------------------------------------------------+
bool CheckTradingConditions()
{
    string vtp_key_buy = GetGlobalVarKey("", "0");
    string vtp_key_sell = GetGlobalVarKey("", "1");
    
    if (GlobalVariableGet(vtp_key_buy) == 1.0 || GlobalVariableGet(vtp_key_sell) == 1.0)
        return true;
    
    return false;
}


//+------------------------------------------------------------------+
//| 检查持仓是否存在 (原lizongs2函数)
//+------------------------------------------------------------------+
bool CheckPositionExists(string symbol, int type, int magic, int mode, string comment)
{
    string check_symbol = symbol;
    if (g_current_symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    int total_positions = PositionsTotal();
    
    for (int i = 0; i < total_positions; i++)
    {
        ulong ticket = PositionGetTicket(i);
        if (!PositionSelectByTicket(ticket))
            continue;
        
        string pos_symbol = PositionGetString(POSITION_SYMBOL);
        string pos_comment = PositionGetString(POSITION_COMMENT);
        int pos_type = (int)PositionGetInteger(POSITION_TYPE);
        int pos_magic = (int)PositionGetInteger(POSITION_MAGIC);
        
        if ((pos_symbol != check_symbol && check_symbol != ""))
            continue;
        
        if ((StringFind(pos_comment, comment, 0) < 0 && comment != ""))
            continue;
        
        if ((pos_type != POSITION_TYPE_BUY && pos_type != POSITION_TYPE_SELL))
            continue;
        
        if ((type >= 0 && pos_type != type))
            continue;
        
        if ((magic >= 0 && pos_magic != magic))
            continue;
        
        if ((mode == ticket || mode == 0))
            return true;
    }
    return false;
}

//+------------------------------------------------------------------+
//| 获取持仓量 (原lizongs3函数)
//+------------------------------------------------------------------+
double GetPositionVolume(string symbol, int type, int magic)
{
    double total_volume = 0.0;
    string check_symbol = symbol;
    
    if (g_current_symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && PositionGetInteger(POSITION_TYPE) != type))
            continue;
            
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL))
            continue;
            
        if ((magic < 0 || PositionGetInteger(POSITION_MAGIC) == magic))
        {
            total_volume += PositionGetDouble(POSITION_VOLUME);
        }
    }
    
    return total_volume;
}

//+------------------------------------------------------------------+
//| 修改止盈 (原lizongs4函数)
//+------------------------------------------------------------------+
void ModifyTakeProfit(int type, int magic, double take_profit)
{
    string check_symbol = g_current_symbol;
    if (g_current_symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        int position_type = (int)PositionGetInteger(POSITION_TYPE);
        if (position_type >= 2)
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && position_type != type))
            continue;
            
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic))
            continue;
            
        // 修改止盈价格
        g_trade.PositionModify(PositionGetTicket(i), PositionGetDouble(POSITION_SL), take_profit);
    }
}

//+------------------------------------------------------------------+
//| 获取交易时间 (原lizongs5函数)
//+------------------------------------------------------------------+
string GetTradingTime()
{
    datetime current_time = TimeCurrent();
    int holiday_days = 0;
    
    if (NewYearHolidays == NY_DAYS_14)
    {
        holiday_days = 15;
    }
    else if (NewYearHolidays == NY_DAYS_7)
    {
        holiday_days = 8;
    }
    else
    {
        holiday_days = 0;
    }
    
    MqlDateTime dt;
    TimeToStruct(current_time, dt);
    
    if ((dt.day_of_year < holiday_days || dt.day_of_year > 358))
    {
        return "Christmas and NY holidays";
    }
    
    return "";
}



//+------------------------------------------------------------------+
//| 计算手数 (原lizong_16函数)
//+------------------------------------------------------------------+
double CalculateLotSize(double base_lot, bool use_martin)
{
    // 原MQL4: lizong_16(double para_0_do, bool para_2_bo)
    double lot_size;
    string author_string;
    string tmp_string1, tmp_string2;
    double min_lot, max_lot, lot_step;
    double balance_base, virtual_balance;
    double risk_amount, value_per_pip, pip_value;
    double calculated_lot;
    int digits;
    int total_orders, order_index;
    int order_type;
    double order_lots;
    
    // 原MQL4: 初始化变量
    author_string = " 作者函数: ";
    calculated_lot = 0.0;
    min_lot = 0.0;
    max_lot = 0.0;
    lot_step = 0.0;
    order_index = 0;
    order_type = 0;
    order_lots = 0.0;
    
    // 原MQL4: 确定小数位数
    if (SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN) == 0.01)
    {
        digits = 2;
    }
    else
    {
        digits = 1;
    }
    
    // 原MQL4: 获取最小手数
    min_lot = SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN);
    if (Lots < min_lot)
    {
        Lots = min_lot;
    }
    
    // 原MQL4: 设置基础手数
    lot_size = g_lot_multiplier;
    
    // 原MQL4: 如果使用风险计算
    if (g_virtual_tp_coeff3 != 0.0)
    {
        // 原MQL4: 确定余额基础
        if (FixedBalance > 0.0)
        {
            balance_base = FixedBalance;
        }
        else
        {
            if (BalanceBaseType == BALANCE_BASE_EQUITY)
            {
                balance_base = AccountInfoDouble(ACCOUNT_EQUITY);
            }
            else
            {
                balance_base = AccountInfoDouble(ACCOUNT_BALANCE);
            }
        }
        
        // 原MQL4: 添加虚拟余额
        virtual_balance = balance_base + VirtualBalance;
        risk_amount = g_virtual_tp_coeff3;
        value_per_pip = SymbolInfoDouble(g_current_symbol, SYMBOL_TRADE_TICK_VALUE);
        pip_value = 0.0;
        
        // 原MQL4: 计算点值
        if (SymbolInfoDouble(g_current_symbol, SYMBOL_POINT) != 0.0)
        {
            pip_value = SymbolInfoDouble(g_current_symbol, SYMBOL_BID) / SymbolInfoDouble(g_current_symbol, SYMBOL_POINT);
        }
        
        // 原MQL4: 计算手数
        if (pip_value * value_per_pip == 0.0)
        {
            PrintFormat(g_current_symbol + " bidcorr*ValuePerPip==0");
            calculated_lot = 0.0;
        }
        else
        {
            calculated_lot = risk_amount * virtual_balance / (pip_value * value_per_pip);
        }
        
        lot_size = calculated_lot * g_lot_multiplier;
    }
    else
    {
        // 原MQL4: 使用固定手数或马丁格尔手数
        if (FirstNumber > 0 && LotsMartinRatio > 0.0)
        {
            lot_size = Lots / MathPow(LotsMartinRatio, FirstNumber);
        }
        else
        {
            lot_size = Lots;
        }
    }
    
    // 原MQL4: 如果需要规范化手数
    if (use_martin)
    {
        lot_size = NormalizeDouble(lot_size, digits);
    }
    
    return lot_size;
}


//+------------------------------------------------------------------+
//| 获取交易信号 (原lizong_12函数)
//+------------------------------------------------------------------+
int GetTradingSignal()
{
    // 原MQL4: lizong_12()
    int signal = 0;
    
    // 原MQL4: 获取市场信息
    g_symbol_spread = (double)SymbolInfoInteger(g_current_symbol, SYMBOL_SPREAD);
    g_symbol_spread_points = g_symbol_spread * SymbolInfoDouble(g_current_symbol, SYMBOL_POINT);
    g_symbol_ask = SymbolInfoDouble(g_current_symbol, SYMBOL_ASK);
    g_symbol_bid = SymbolInfoDouble(g_current_symbol, SYMBOL_BID);
    g_symbol_point = SymbolInfoDouble(g_current_symbol, SYMBOL_POINT);
    
    // 原MQL4: global_130_do = 0.0;
    g_symbol_commission = 0.0;
    double prev_close = iClose(g_current_symbol, PERIOD_CURRENT, 1);
    if (prev_close > 0.0)
    {
        // 原MQL4: global_130_do = (MathAbs(global_127_do / iClose(global_50_st, 0, 1) - 1.0)) * 10000.0;
        g_symbol_commission = MathAbs(g_symbol_bid / prev_close - 1.0) * 10000.0;
    }
    
    // 原MQL4: 买入信号检查 (global_127_do > global_55_do)
    if (g_symbol_bid > g_upper_band)
    {
        // 原MQL4: ObjectDelete(0, "DD");
        ObjectDelete(0, "DD");
        
        // 原MQL4: if ((FirstPositionp == 1 || FirstPositionp == 3))
        // 注意：MQL4返回2表示买入信号，检查是否允许开多单应该是 1 || 2
        if (FirstPositionType == FIRST_POS_LONG_AND_SHORT || FirstPositionType == FIRST_POS_LONG)
        {
            signal = 2; // 买入信号 (原MQL4中返回2表示买入)
            
            // 原MQL4: 计算虚拟止盈价格
            // global_53_do = 0.00001 / global_128_do * MathPow(global_31_do, MathLog(global_18_in / 100.0) / 0.6931471805599) * global_30_in / MathPow(global_31_do, 2.0) * global_127_do + global_28_do * MathPow(global_29_do, global_14_in) * (global_127_do - global_56_do) / global_128_do;
            g_virtual_tp_price = 0.00001 / g_symbol_point * 
                                            MathPow(g_tp_price_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) *
            g_unlock_percent / MathPow(g_tp_price_coefficient, 2.0) * g_symbol_bid + 
                                g_lot_divider * MathPow(g_martin_coefficient, g_grid_level) * 
                                (g_symbol_bid - g_ma_value) / g_symbol_point;
        }
    }
    
    // 原MQL4: 卖出信号检查 (global_126_do < global_57_do)
    // global_57_do = MA - StdDev (下轨)
    if (g_symbol_ask < g_lower_band)
    {
        // 原MQL4: ObjectDelete(0, "DD");
        ObjectDelete(0, "DD");
        
        // 原MQL4: if ((FirstPositionp == 1 || FirstPositionp == 2))
        if (FirstPositionType == FIRST_POS_LONG_AND_SHORT || FirstPositionType == FIRST_POS_SHORT)
        {
            signal = 1; // 卖出信号 (原MQL4中返回1表示卖出)
            
            // 原MQL4: 计算虚拟止盈价格
            // global_53_do = 0.00001 / global_128_do * MathPow(global_31_do, MathLog(global_18_in / 100.0) / 0.6931471805599) * global_30_in / MathPow(global_31_do, 2.0) * global_127_do + global_28_do * MathPow(global_29_do, global_14_in) * (global_56_do - global_127_do) / global_128_do;
            g_virtual_tp_price = 0.00001 / g_symbol_point * 
                                            MathPow(g_tp_price_coefficient, MathLog(g_ma_period / 100.0) / 0.6931471805599) *
            g_unlock_percent / MathPow(g_tp_price_coefficient, 2.0) * g_symbol_bid + 
                                g_lot_divider * MathPow(g_martin_coefficient, g_grid_level) * 
                                (g_ma_value - g_symbol_bid) / g_symbol_point;
        }
    }
    
    return signal;
}

//+------------------------------------------------------------------+
//| 更新虚拟订单 (原lizong80函数)
//+------------------------------------------------------------------+
void UpdateVirtualOrder(int order_ticket)
{
    // 原MQL4: lizong80(int local_8_in)
    if (MQLInfoInteger(MQL_TESTER) && g_enable_test_mode)
    {
        // 原MQL4: global_86_st_si40000[global_88_in] = "C" + string(global_14_in) + "," + string(global_18_in) + "," + string(global_58_do / MarketInfo(global_50_st, 9));
        g_string_array[g_array_index_1] = "C" + IntegerToString(g_min_real_level) + "," + 
                                         IntegerToString(g_ma_period) + "," + 
                                         DoubleToString(g_stddev_value / SymbolInfoDouble(g_current_symbol, SYMBOL_BID), 2);
        
        // 原MQL4: global_87_in_si40000[global_88_in] = local_8_in;
        g_int_array[g_array_index_1] = order_ticket;
        
        // 原MQL4: global_88_in++;
        g_array_index_1++;
    }
}

//+------------------------------------------------------------------+
//| 更新界面显示 (原lizong_27函数)
//+------------------------------------------------------------------+
void UpdateInterfaceDisplay()
{
    // 原MQL4: lizong_27()
    string current_symbol;
    double total_profit, total_lots, leverage_ratio, profit_percent;
    double spread_value, balance_value, equity_value, virtual_balance;
    string balance_string, equity_string, profit_string;
    double usdcad_value, usd_equivalent;
    string usd_string;
    bool trading_disabled;
    
    // 原MQL4: 确定当前符号
    if (ArraySize(g_symbol_list) > 1)
    {
        current_symbol = "";
    }
    else
    {
        current_symbol = g_current_symbol;
    }
    
    // 原MQL4: 计算总盈利 (买单)
    total_profit = CalculateTotalProfit(current_symbol, -1, -1);
    
    // 原MQL4: 计算总手数 (买单)
    total_lots = CalculateTotalLots(current_symbol, -1, -1);
    
    // 原MQL4: 计算杠杆比率
    if (SymbolInfoDouble(current_symbol, SYMBOL_TRADE_TICK_VALUE) == 0.0)
    {
        leverage_ratio = 0.0;
    }
    else
    {
        double account_equity = AccountInfoDouble(ACCOUNT_EQUITY);
        if (account_equity > 0.0)
        {
            leverage_ratio = SymbolInfoDouble(current_symbol, SYMBOL_BID) / SymbolInfoDouble(current_symbol, SYMBOL_TRADE_TICK_VALUE) * 
                           SymbolInfoDouble(current_symbol, SYMBOL_TRADE_TICK_VALUE) * total_lots / account_equity;
        }
        else
        {
            leverage_ratio = 0.0;
        }
    }
    
    // 原MQL4: 计算盈利百分比
    double account_balance = AccountInfoDouble(ACCOUNT_BALANCE);
    if (account_balance > 0.0)
    {
        profit_percent = total_profit / account_balance;
    }
    else
    {
        profit_percent = 0.0;
    }
    
    // 原MQL4: 获取账户信息
    spread_value = SymbolInfoInteger(NULL, SYMBOL_SPREAD);
    balance_value = AccountInfoDouble(ACCOUNT_BALANCE);
    equity_value = AccountInfoDouble(ACCOUNT_EQUITY);
    virtual_balance = balance_value + VirtualBalance;
    
    // 原MQL4: 格式化字符串
    balance_string = DoubleToString(balance_value, 0);
    equity_string = DoubleToString(virtual_balance, 0);
    profit_string = DoubleToString(equity_value + VirtualBalance, 0);
    
    // 原MQL4: 计算USD等值
    if (SymbolInfoDouble("USDCAD", SYMBOL_TRADE_TICK_VALUE) == 0.0)
    {
        usdcad_value = 0.0;
    }
    else
    {
        if (1000.0 > 0.0)
        {
            usdcad_value = SymbolInfoDouble("USDCAD", SYMBOL_BID) / SymbolInfoDouble("USDCAD", SYMBOL_TRADE_TICK_VALUE) * 
                          SymbolInfoDouble("USDCAD", SYMBOL_TRADE_TICK_VALUE) * 0.01 / 1000.0;
        }
        else
        {
            usdcad_value = 0.0;
        }
    }
    
    if (usdcad_value > 0.0)
    {
        usd_equivalent = balance_value / usdcad_value;
        if (AccountInfoString(ACCOUNT_CURRENCY) == "USD")
        {
            usd_string = "";
        }
        else
        {
            usd_string = " ~$" + DoubleToString(usd_equivalent, 0);
        }
        balance_string += usd_string;
    }
    
    // 原MQL4: 更新界面对象
    if (VirtualBalance != 0.0 && USDFor001 > 0.0)
    {
        if (ObjectSetString(0, "FullBalance", OBJPROP_TEXT, equity_string))
        {
            ChartRedraw(0);
        }
        if (ObjectSetString(0, "FullEquity", OBJPROP_TEXT, profit_string))
        {
            ChartRedraw(0);
        }
    }
    
    if (ObjectSetString(0, "OpenLots", OBJPROP_TEXT, DoubleToString(total_lots, 2)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "CurrLev", OBJPROP_TEXT, "1:" + DoubleToString(leverage_ratio, 1)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "FloatProf%", OBJPROP_TEXT, StringFormat("%+.1f%%", profit_percent * 100.0)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "Balance", OBJPROP_TEXT, balance_string))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "Equity", OBJPROP_TEXT, DoubleToString(equity_value, 1)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "FloatProf", OBJPROP_TEXT, StringFormat("%+.1f", total_profit)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "TradingMode", OBJPROP_TEXT, GetTradingModeString()))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "Sizelot", OBJPROP_TEXT, DoubleToString(CalculateLotSize(1.0, false) * MathPow(LotsMartinRatio, FirstNumber), 3)))
    {
        ChartRedraw(0);
    }
    
    if (ObjectSetString(0, "spread", OBJPROP_TEXT, DoubleToString(spread_value, 0)))
    {
        ChartRedraw(0);
    }
    
    // 原MQL4: 检查交易状态
    trading_disabled = false;
    if (Period() != PERIOD_M15)
    {
        trading_disabled = true;
    }
    if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
    {
        trading_disabled = true;
    }
    if (AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) == 0)
    {
        trading_disabled = true;
    }
    if (TerminalInfoInteger(TERMINAL_CONNECTED) == 0)
    {
        trading_disabled = true;
    }
    
    if (trading_disabled)
    {
        ObjectSetInteger(0, "RectLabel", OBJPROP_BGCOLOR, 17919);
        return;
    }
    
    ObjectSetInteger(0, "RectLabel", OBJPROP_BGCOLOR, 8421376);
}

//+------------------------------------------------------------------+
//| 计算动态标准差 (原lizongs11函数)
//+------------------------------------------------------------------+
double CalculateDynamicStdDev(int level, int period)
{
    int symbol_index = 0;
    double coeff1 = 0.0;
    double coeff2 = 0.0;
    double min_lot = SymbolInfoDouble(g_current_symbol, SYMBOL_VOLUME_MIN);
    
    // 根据符号确定索引
    if (StringFind(g_current_symbol, "AUDCAD", 0) >= 0)
    {
        symbol_index = 0;
    }
    else if (StringFind(g_current_symbol, "AUDNZD", 0) >= 0)
    {
        symbol_index = 1;
    }
    else if (StringFind(g_current_symbol, "NZDCAD", 0) >= 0)
    {
        symbol_index = 2;
    }
    else if (StringFind(g_current_symbol, "GBPCAD", 0) >= 0)
    {
        symbol_index = 3;
    }
    else if (StringFind(g_current_symbol, "EURGBP", 0) >= 0)
    {
        symbol_index = 4;
    }
    else
    {
        symbol_index = 5;
    }
    
    // 检查条件
    if ((level < 0 || level > 4 || symbol_index == -1 || Period() != PERIOD_M15))
    {
        return -1.0;
    }
    
    coeff1 = g_3d_array[symbol_index][level][0];
    coeff2 = g_3d_array[symbol_index][level][1];
    
    return (coeff1 * MathPow(period, coeff2) * min_lot);
}

//+------------------------------------------------------------------+
//| 获取交易模式字符串 (原lizong_28函数)
//+------------------------------------------------------------------+
string GetTradingModeString()
{
    // 原MQL4: lizong_28()
    string mode_string;
    datetime current_time;
    int holiday_days;
    string holiday_string;
    
    // 原MQL4: 检查连接状态
    if (TerminalInfoInteger(TERMINAL_CONNECTED) == 0)
    {
        mode_string = "No connection";
        return mode_string;
    }
    
    // 原MQL4: 检查账户交易权限
    if (AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) == 0)
    {
        mode_string = "Investor mode";
        return mode_string;
    }
    
    // 原MQL4: 检查时间框架
    if (Period() != PERIOD_M15)
    {
        mode_string = "Change timeframe to M15";
        return mode_string;
    }
    
    // 原MQL4: 检查EA交易权限
    if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
    {
        mode_string = "EA trading not allowed";
        return mode_string;
    }
    
    // 原MQL4: 检查快速平仓模式
    if (FastClose)
    {
        mode_string = "EMERGENCY CLOSING!!!";
        return mode_string;
    }
    
    // 原MQL4: 检查首单类型限制
    if (FirstPositionType != FIRST_POS_LONG_AND_SHORT)
    {
        mode_string = "Trade limited. FirstPos=" + EnumToString((EnumFirstPositionType)FirstPositionType);
        return mode_string;
    }
    
    // 原MQL4: 检查ATR条件
    if (!g_trading_allowed)
    {
        mode_string = "ATR > ATR_max. Only close.";
        return mode_string;
    }
    
    // 原MQL4: 检查节假日
    current_time = TimeCurrent();
    holiday_days = 0;
    
    if (NewYearHolidays == NY_DAYS_14)
    {
        holiday_days = 15;
    }
    else if (NewYearHolidays == NY_DAYS_7)
    {
        holiday_days = 8;
    }
    else
    {
        holiday_days = 0;
    }
    
    MqlDateTime dt;
    TimeToStruct(current_time, dt);
    
    if ((dt.day_of_year < holiday_days || dt.day_of_year > 358))
    {
        holiday_string = "Christmas and NY holidays";
    }
    else
    {
        holiday_string = "";
    }
    
    if (holiday_string != "")
    {
        mode_string = holiday_string;
        return mode_string;
    }
    
    // 原MQL4: 检查可视化模式
    if (MQLInfoInteger(MQL_VISUAL_MODE))
    {
        mode_string = "Backtesting in Visual Mode";
        return mode_string;
    }
    
    // 原MQL4: 默认模式
    mode_string = "Live Trading";
    return mode_string;
}

//+------------------------------------------------------------------+
//| 计算总盈利 (用于界面显示)
//+------------------------------------------------------------------+
double CalculateTotalProfit(string symbol, int type, int magic)
{
    double total_profit = 0.0;
    string check_symbol = symbol;
    
    if (symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && PositionGetInteger(POSITION_TYPE) != type))
            continue;
            
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL))
            continue;
            
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic))
            continue;
            
        total_profit += PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP) + PositionGetDouble(POSITION_COMMISSION);
    }
    
    return total_profit;
}

//+------------------------------------------------------------------+
//| 计算总手数 (用于界面显示)
//+------------------------------------------------------------------+
double CalculateTotalLots(string symbol, int type, int magic)
{
    double total_lots = 0.0;
    string check_symbol = symbol;
    
    if (symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && PositionGetInteger(POSITION_TYPE) != type))
            continue;
            
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL))
            continue;
            
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic))
            continue;
            
        total_lots += PositionGetDouble(POSITION_VOLUME);
    }
    
    return total_lots;
}

//+------------------------------------------------------------------+
//| 平掉所有持仓 (原lizong_17函数)
//+------------------------------------------------------------------+
void CloseAllPositions(string symbol, int type, int magic)
{
    // 原MQL4: lizong_17(string para_0_st, int para_1_in, int para_2_in)
    string check_symbol = symbol;
    
    if (symbol == "0")
    {
        check_symbol = g_current_symbol;
    }
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (!PositionSelectByTicket(PositionGetTicket(i)))
            continue;
            
        if ((PositionGetString(POSITION_SYMBOL) != check_symbol && check_symbol != ""))
            continue;
            
        if ((type >= 0 && PositionGetInteger(POSITION_TYPE) != type))
            continue;
            
        if ((PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_BUY && PositionGetInteger(POSITION_TYPE) != POSITION_TYPE_SELL))
            continue;
            
        if ((magic >= 0 && PositionGetInteger(POSITION_MAGIC) != magic))
            continue;
            
        // 平仓
        g_trade.PositionClose(PositionGetTicket(i));
    }
}